Converting Array to String to Array

I have an array that I store as a string in a database to make it easier to get it (updated with new data every 15-30 minutes via cron).

'player_list' -> 'Bob,Dave,Jane,Gordy'
'plugin_list' -> 'Plugin-A 1.4, Plugin-B 2.1, Plugin-C 0.2'

      

I originally stored the array in db as a string using:

 $players = $liveInfo['players'] ? implode(",", $liveInfo['players']) : '';

 $plugins = $liveInfo['plugins'] ? implode(",", $liveInfo['plugins']) : '';

      

I am currently using the following to restore and then convert the string back to an array in preparation for the foreach:

 $players = $server_live->player_list;
 $playersArray = explode(",", $players);
 $plugins = $server_live->plugin_list;
 $pluginsArray = explode(",", $plugins);

      

For some reason, I am getting the following error: Array to string conversion

I don't understand this error as I am going from String to Array and I looked php.net/manual

and it looks ok? ...

+3


source to share


2 answers


If you need to convert from Object to String and from String to Object, then you need to do serialization and you must support its object.

in your case, using arrays is serialization supported.

Array for string

$strFromArr = serialize($Arr);

      



String to array

$Arr = unserialize($strFromArr);

      

for more information, consider browsing the php.net website: serialize unserialize p>

+12


source


If you have to do it your own way, store the array in the database, use the function serialize()

. It's amazing!

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



$string = serialize($array);

$array = unserialize($string);

+2


source







All Articles