我环顾四周但没有找到答案,所以我想我会自己问一下。
我注意到JSON往返将2-D数组转换为1D对象数组。
有没有办法解决这个问题,或者我是否应该尝试从头开始处理对象(例如$ test-> 1-> 4?请参阅下面的示例
$test = array();
$test[0][0] = "0-0";
$test[0][2] = "0-2";
$test[1][1] = "1-1";
$test[1][2] = "1-2";
var_dump($test);
$encoded = json_encode($test);
var_dump($encoded);
$recreated = json_decode($encoded);
var_dump($recreated);
输出
array(2) {
[0]=>
array(2) {
[0]=>
string(3) "0-0"
[2]=>
string(3) "0-2"
}
[1]=>
array(2) {
[1]=>
string(3) "1-1"
[2]=>
string(3) "1-2"
}
}
string(45) "[{"0":"0-0","2":"0-2"},{"1":"1-1","2":"1-2"}]"
array(2) {
[0]=>
object(stdClass)#19 (2) {
["0"]=>
string(3) "0-0"
["2"]=>
string(3) "0-2"
}
[1]=>
object(stdClass)#20 (2) {
["1"]=>
string(3) "1-1"
["2"]=>
string(3) "1-2"
}
}
答案 0 :(得分:2)
这是因为您的数组中没有正在进行的索引:
$test = array();
$test[0][0] = "0-0";
$test[0][2] = "0-2";
在这种情况下json_encode()
创建一个对象,因为缺少一个数字键(1)。
您可以使用json_decode($txt, true)
将其解码回数组,但这只是一种解决方法,而非修复方法。
答案 1 :(得分:0)
默认情况下,json_decode会将json转换为对象。您的代码需要看起来像:
$recreated = json_decode($encoded, true);
答案 2 :(得分:0)
您可以解码为数组:
$recreated = json_decode($encoded, true);