如何摆脱PHP中数组中的索引数量

时间:2013-04-30 09:21:15

标签: php mysql sql database json

Hello我有一个数组,其中包含其他两个数组,使用以下代码:

    foreach($relations as $rel){
        $data[$i]["relationTo"] = $rel["name"];
        $data[$i]["relation"] = $rel["relation"];
        $i = $i+1;
    }
    foreach($relations as $rel){
        $children[$i]["id"] = $rel["id2"];
        $children[$i]["name"] = $rel["sname"];
        $children[$i]["data"] = $data;
        $i = $i+1;
    }
    foreach($relations as $rel){
        $relationArray[$i]["id"] = $rel["id"];
        $relationArray[$i]["name"] = $rel["name"];
        $relationArray[$i]["children"] = $children;
        $i = $i+1;
    }

当我使用以下方式打印出来时

print_r($relationArray);

它打印以下内容:

Array ( [2] => Array ( [id] => 4 [name] => Albaraa [children] => 
Array ( [1] => Array (      [id] => 5 [name] => Sadi [data] => 
Array ( [0] => Array ( [relationTo] => Albaraa [relation] => Father ) ) ) ) ) )

我正在使用json_encode,我需要以某种方式在json中输出,不包括开头的数组索引计数...当我使用时json输出:

echo json_encode($relationArray);

目前是这样的:

 {"2":{"id":"4","name":"Albaraa","children":
 {"1":{"id":"5","name":"Sadi","data":  [{"relationTo":"Albaraa","relation":"Father"}]}}}}

在前两个数组的前面有“2”和“1”...这不是我想要实现的那样:

 {"id":"4","name":"Albaraa","children":
 {"id":"5","name":"Sadi","data":  [{"relationTo":"Albaraa","relation":"Father"}]}}}}

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

几种解决方案

1)不要通过[$i]输入值,准备新的完整内部数组并将其放入array_push中

2)如果你仍然想这样做,你只能提取值:

print_r(json_encode(array_values($array)));