【问题标题】:nested array into simple nested array in php嵌套数组到php中的简单嵌套数组
【发布时间】:2016-04-04 16:27:23
【问题描述】:

我有一个数组

[0] => array(3) {
    ["id"] => string(1) "2"
    ["name"] => string(10) "Contractor"
    ["statuses"] => array(4) {
      [1] => array(3) {
        ["id"] => string(1) "1"
        ["name"] => string(3) "NEW"
        ["count"] => string(2) "32"
      }
      [3] => array(3) {
        ["id"] => string(1) "3"
        ["name"] => string(8) "RETURNED"
        ["count"] => string(2) "20"
      }
      [5] => array(3) {
        ["id"] => string(1) "5"
        ["name"] => string(6) "FAILED"
        ["count"] => string(2) "46"
      }
      [58] => array(3) {
        ["id"] => string(2) "58"
        ["name"] => string(6) "REVISE"
        ["count"] => string(3) "197"
      }
    }
  }

现在当我转换成 JSON 时,它看起来像这样

"items":[{"id":"2","name":"Contractor","statuses":{"1":{"id":"1","name":"NEW","count":"32"},"3":{"id":"3","name":"RETURNED","count":"20"},"5":{"id":"5","name":"FAILED","count":"46"},"58":{"id":"58","name":"REVISE","count":"197"}}}...

如何从数组或 JSON 中删除前面的 1、3、6 和 58

我试过array_values(),但它没有转换数组的嵌套部分

【问题讨论】:

  • 所以你基本上需要unset statuses?
  • documentation 很好地回答了你的问题。
  • 不,我只是想删除那个 [1],[3],...[58]从嵌套数组
  • 试试$array['statuses'] = array_values($array['statuses'])

标签: php arrays json multidimensional-array


【解决方案1】:

如何从数组或 json 中删除前面的 1、3、6 和 58

如果您希望json_encode() 返回 JSON 数组,则所有数组键必须:

  • 是数字
  • 按顺序排列
  • 序列必须从0开始

例如:

$a = [1,2,3];
echo json_encode($a);

需要的输出

[1,2,3]

与显式设置的索引相同:

$a = [0=>1,2,3];

但是

$a = [1=>1,2,3];

将输出对象:

{"1":1,"2":2,"3":3}

因为序列不是从0 开始的。你的情况也一样:

$a = [1,2,58=>3];

产生

{"0":1,"1":2,"58":3}

因为索引58破坏了键序列的连续性。

因此,根据您构建源数组的方式,只需使用 array_values() 删除自己的键:

$a = [1,2,58=>3];
echo json_encode(array_values($a)]);

会产生

[1,2,3]

所以在你的$data['statuses'] 上使用array_values() 就完成了。

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    相关资源
    最近更新 更多