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

MCG*_*MCG 8 php mysql arrays string laravel-3

我有一个数组,我将其作为字符串存储在数据库中,以便更容易检索(通过cron每15-30分钟刷新一次新数据).

'player_list' -> 'Bob,Dave,Jane,Gordy'
'plugin_list' -> 'Plugin-A 1.4, Plugin-B 2.1, Plugin-C 0.2'
Run Code Online (Sandbox Code Playgroud)

我最初使用以下方法将数组作为字符串存储到数据库中:

 $players = $liveInfo['players'] ? implode(",", $liveInfo['players']) : '';

 $plugins = $liveInfo['plugins'] ? implode(",", $liveInfo['plugins']) : '';
Run Code Online (Sandbox Code Playgroud)

我目前正在使用以下内容进行检索,然后将字符串转换回数组以准备foreach:

 $players = $server_live->player_list;
 $playersArray = explode(",", $players);
 $plugins = $server_live->plugin_list;
 $pluginsArray = explode(",", $plugins);
Run Code Online (Sandbox Code Playgroud)

由于某种原因,我收到以下错误:Array to string conversion 我不明白这个错误,因为我要从String转到数组,我看了看php.net/manual它看起来很好吗?...

Abu*_*sae 18

如果你需要从Object转换为String,从String转换为Object,那么你需要进行序列化,而你的对象应该支持它.

在您的情况下,使用数组,支持序列化.

数组到字符串

$strFromArr = serialize($Arr);
Run Code Online (Sandbox Code Playgroud)

字符串到数组

$Arr = unserialize($strFromArr);
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅php.net网站:serialize unserialize