我有一个JSON数组,我保存在一个PHP变量。然后,我使用serialize($variable)
序列化该数组,并使用内置的Wordpress函数update_post_meta()
将其保存到dB。
我遇到的问题是整个序列化数组都用字符串计数包装。如下所示,当前保存为:
s:332:"a:2:{i:0;a:7:{s:4:"type";s:5:"weeks";s:4:"cost";s:1:"3";s:8:"modifier";s:0:"";s:9:"base_cost";s:1:"2";s:13:"base_modifier";s:0:"";s:4:"from";s:1:"1";s:2:"to";s:1:"4";}i:1;a:7:{s:4:"type";s:7:"persons";s:4:"cost";s:1:"6";s:8:"modifier";s:0:"";s:9:"base_cost";s:1:"5";s:13:"base_modifier";s:0:"";s:4:"from";s:1:"1";s:2:"to";s:1:"2";}}";
我需要保存它而不包含整个数组的字符串计数。期望输出值:
a:2:{i:0;a:7:{s:4:"type";s:5:"weeks";s:4:"cost";s:1:"3";s:8:"modifier";s:0:"";s:9:"base_cost";s:1:"2";s:13:"base_modifier";s:0:"";s:4:"from";s:1:"1";s:2:"to";s:1:"4";}i:1;a:7:{s:4:"type";s:7:"persons";s:4:"cost";s:1:"6";s:8:"modifier";s:0:"";s:9:"base_cost";s:1:"5";s:13:"base_modifier";s:0:"";s:4:"from";s:1:"1";s:2:"to";s:1:"2";}};
如有任何帮助,我将一如既往地感激不尽。
似乎你的数组被序列化了两次,这就是给你附录的原因…我已经获取了你的序列化数据,并将其反序列化了两次,它返回了你想要的结果:
<?php
$ser = 's:332:"a:2:{i:0;a:7:{s:4:"type";s:5:"weeks";s:4:"cost";s:1:"3";s:8:"modifier";s:0:"";s:9:"base_cost";s:1:"2";s:13:"base_modifier";s:0:"";s:4:"from";s:1:"1";s:2:"to";s:1:"4";}i:1;a:7:{s:4:"type";s:7:"persons";s:4:"cost";s:1:"6";s:8:"modifier";s:0:"";s:9:"base_cost";s:1:"5";s:13:"base_modifier";s:0:"";s:4:"from";s:1:"1";s:2:"to";s:1:"2";}}";';
$arr = unserialize($ser);
echo '<pre>';
print_r($arr); /* Print after one unserialize */
echo '<pre>';
print_r(unserialize($arr)); /* Print with unserialize to the once unserialized*/
将返回:
a:2:{i:0;a:7:{s:4:"type";s:5:"weeks";s:4:"cost";s:1:"3";s:8:"modifier";s:0:"";s:9:"base_cost";s:1:"2";s:13:"base_modifier";s:0:"";s:4:"from";s:1:"1";s:2:"to";s:1:"4";}i:1;a:7:{s:4:"type";s:7:"persons";s:4:"cost";s:1:"6";s:8:"modifier";s:0:"";s:9:"base_cost";s:1:"5";s:13:"base_modifier";s:0:"";s:4:"from";s:1:"1";s:2:"to";s:1:"2";}}
Array
(
[0] => Array
(
[type] => weeks
[cost] => 3
[modifier] =>
[base_cost] => 2
[base_modifier] =>
[from] => 1
[to] => 4
)
[1] => Array
(
[type] => persons
[cost] => 6
[modifier] =>
[base_cost] => 5
[base_modifier] =>
[from] => 1
[to] => 2
)
)
正如你所看到的,只有在两次反序列化之后,它才返回到一个数组…所以只要做一个,你就得到了你需要的。