开发者

The way to store association array into MySQL and retrieve it back in PHP?

开发者 https://www.devze.com 2023-02-13 08:06 出处:网络
E.g: 开发者_JAVA技巧PHP code:strong text // $files would be stored into mysql db and will retrieve as original

E.g:

开发者_JAVA技巧PHP code:strong text

// $files would be stored into mysql db and will retrieve as original
$files = array('1' => '1,2,4,5', '5' => '4,5,7,23,56','8' => '45,23,56,67');

And the database table file's allFile[char]

'1' => '1,2,4,5', '5' => '4,5,7,23,56','8' => '45,23,56,67' 

I thought I must convert the array data into string and then store into database,but implode only got the array value without key.So, should I use the foreach loop to get the key/value into string?

foreach ($files as $key => $value){
  $str .= $key.'=>'.$value.','; // remove the last comma of the $str
}

and when I retrieve $str form database, I get:

$files = array($str); 

So, am I do the right way ?!

Thank you very much!!


json_encode/json_decode are a popular choice here, as it means the database content is still readable without PHP. In my quick tests, storing as JSON is also more efficient.


$string = serialize($array);
$array = unserialize($string);

http://php.net/manual/ru/function.serialize.php

http://php.net/manual/ru/function.unserialize.php

0

精彩评论

暂无评论...
验证码 换一张
取 消