开发者

Converting array to string and then back in PHP

I created a array using PHP

$userarray = array('UserName'=>$username,'User开发者_StackOverflowId'=>$userId,'UserPicURL'=>$userPicURL);

How can I convert this array into a string in PHP and back from string into an array. This is kind of a requirement. Could someone please advice on how this can be acheived.


You can convert any PHP data-type but resources into a string by serializing it:

$string = serialize($array);

And back into it's original form by unserializing it again:

$array = unserialize($string);

A serialized array is in string form. It can be converted into an array again by unserializing it.

The same does work with json_encode / -_decode for your array as well:

$string = json_encode($array);
$array = json_decode($string);


use the function implode(separator,array) which return a string from the elements of an array.

and then the function explode ( string $delimiter , string $string [, int $limit ] ) to revert it back to an array

$array_as_string = implode(" ",$userarray);
$new_array = explode(" ",$array_as_string);


You can use either

$userarray = array('UserName' => $username, 'UserId' => $userId, 'UserPicURL' => $userPicURL);
$string = json_encode($userarray);
$backtoarray = json_decode($string);

or

$userarray = array('UserName' => $username, 'UserId' => $userId, 'UserPicURL' => $userPicURL);
$string = serialize($userarray);
$backtoarray = unserialize($string);

The first one uses XML storage, and the second uses JSON.


this worked for me to get array again:

$backtoarray = (array) json_decode($string);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜