Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array to String to Array conversion

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

like image 427
MCG Avatar asked Feb 16 '13 13:02

MCG


People also ask

How do I turn an array into a string array?

To convert an array of numbers to an array of strings, call the map() method on the array, and on each iteration, convert the number to a string. The map method will return a new array containing only strings.

How do I convert a string to an array in JavaScript?

The string in JavaScript can be converted into a character array by using the split() and Array. from() functions.

How do I convert an array to a string in Matlab?

str = string( A ) converts the input array to a string array. For instance, if A is numeric vector [1 20 300] , str is a string array of the same size, ["1" "20" "300"] . str = string( A , dateFmt ) , where A is a datetime or duration array, applies the specified format, such as "HH:mm:ss" .


2 Answers

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

like image 80
Abu Romaïssae Avatar answered Oct 09 '22 14:10

Abu Romaïssae


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);

like image 31
Prash Avatar answered Oct 09 '22 15:10

Prash