JSON中的2D数组转换为对象的1D数组 [英] 2D arrays in JSON getting converted into a 1D array of objects

查看:50
本文介绍了JSON中的2D数组转换为对象的1D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾四周,但没有找到答案,所以我想自己问个问题.

I've looked around but haven't found an answer so I figured i would give it an ask myself.

我注意到往返JSON会将2D数组转换为1D对象数组.

I've noticed that a round trip to JSON converts a 2-D array into a 1D array of Objects.

有没有解决的办法,还是应该从一开始就尝试使用对象(例如$ test-> 1-> 4?请参见下面的示例

Is there any way around this or should I just try to work with objects from the beginning (e.g. $test->1->4 ? see example below

    $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"
  }
}

推荐答案

这是因为数组中没有正在进行的索引:

This is because you don't have ongoing indexes in your array:

$test = array();
$test[0][0] = "0-0";
$test[0][2] = "0-2";

在这种情况下,由于缺少数字键(1),因此json_encode()可以创建对象.

In this case json_encode() HAS to create an object because there is a numeric key (1) missing.

您可以使用json_decode($txt, true)将其解码回数组,但这只是解决方法,而不是解决方法.

You can decode it back to an array with json_decode($txt, true), but this is only a work around, not a fix.

这篇关于JSON中的2D数组转换为对象的1D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆