简体   繁体   English

数组到字符串到数组的转换

[英]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). 我有一个数组,我将其作为字符串存储在数据库中,以便更容易检索(通过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 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?... 由于某种原因,我收到以下错误: Array to string conversion我不明白这个错误,因为我要从字符串到数组,我看着php.net/manual ,它看起来很好吗?...

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: serialize unserialize 有关更多信息,请参阅php.net网站: serialize unserialize

If you must do it your way, by storing the array in the database, use the serialize() function. 如果必须按照自己的方式进行操作,则通过将数组存储在数据库中,使用serialize()函数。 It's awesome! 这很棒!

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

$string = serialize($array);

$array = unserialize($string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM