Array to String to Array conversion

MCG picture MCG · Feb 16, 2013 · Viewed 37.9k times · Source

I have an array that I'm storing as a string in a database to make it easier to retrieve (it's refreshed with new data every 15-30minutes via cron).

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

I originally store the array into the db as a string using:

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

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

I am currently using the following to retreive and then convert string back into array in preparation for a 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 since I'm going from String to Array and I looked over the php.net/manual and it looks fine?...

Answer

Abu Romaïssae picture Abu Romaïssae · Feb 16, 2013

If you need to convert from Object to String and from String to Object, then serialization is all you need to do, and you object should be supporting it.

in your case, Using Arrays, serialization is supported.

Array to String

$strFromArr = serialize($Arr);

String to Array

$Arr = unserialize($strFromArr);

for more information consider seeing the php.net website: serialize unserialize