嵌套数组到php中的简单嵌套数组中

时间:2016-04-04 16:27:23

标签: php arrays json multidimensional-array

我有一个数组

[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(),但它没有转换数组的嵌套部分

1 个答案:

答案 0 :(得分:2)

how to i remove the preceding 1, 3, 6 and 58 from array or json

If you want json_encode() to return JSON array all the array keys must:

  • be numeric
  • be in sequence
  • the sequence must start from 0

For example:

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

outputs desired

[1,2,3]

same with explicitly set indexes:

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

but

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

would output object:

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

because sequence does not start from 0. Same for your case:

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

which produces

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

because continuity of the key sequence is broken by index 58.

So depending on how you build your source array simply remove own keys with i.e. array_values():

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

would produce

[1,2,3]

so use array_values() on your $data['statuses'] and you are done.