php 数组到字符串到数组的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/14910746/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array to String to Array conversion
提问by MCG
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).
我有一个数组,我将它作为字符串存储在数据库中,以便于检索(通过 cron 每 15-30 分钟刷新一次新数据)。
'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:
我目前正在使用以下内容来检索,然后将字符串转换回数组以准备 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 conversionI don't understand this error since I'm going from String to Array and I looked over the php.net/manualand it looks fine?...
出于某种原因,我收到以下错误:Array to string conversion我不明白这个错误,因为我从字符串到数组,我查看了php.net/manual它,看起来还不错?...
回答by Abu Roma?ssae
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.
如果您需要从 Object 转换为 String 以及从 String 转换为 Object,那么您需要做的就是序列化,并且您的对象应该支持它。
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: serializeunserialize
回答by Prash
If you must do it your way, by storing the array in the database, use the serialize()function. It's awesome!
如果您必须按照自己的方式进行操作,通过将数组存储在数据库中,请使用该serialize()函数。这很棒!
http://php.net/manual/en/function.serialize.php
http://php.net/manual/en/function.serialize.php
$string = serialize($array);
$string = serialize($array);
$array = unserialize($string);
$array = unserialize($string);

