9

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?...

3
  • You should NOT store multiple data in one database column. You could use text file instead of DB, if you are going to do this. You should find a way how to organize your data correctly. Commented Feb 16, 2013 at 13:20
  • I felt it was fine in my case as the data store is exclusive to a particular row. I'm grabbing a list of online players at the time of ping and storing it as a string for convenience since it is updated every ~15-30minutes. I've thought about a separate table but it'll end up with millions of rows... Commented Feb 16, 2013 at 13:24
  • 1
    If you absolutely must store multiple values in one column, serialize() the array and store the result. Commented Feb 16, 2013 at 13:27

2 Answers 2

18

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

Sign up to request clarification or add additional context in comments.

Comments

3

If you must do it your way, by storing the array in the database, use the serialize() function. It's awesome!

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

$string = serialize($array);

$array = unserialize($string);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.