-2

我正在循环一个多维/嵌套数组,我得到以下结果,但是我想摆脱“1”:每个数组前面的索引号。

{"1":{"adjacencies":[{"nodeTo":"2"},{"nodeTo":"5"}],"data":  {"$color":"#EBB056","$type":"star"},"id":1,"name":"rootWarbler<\/label>"},
"2":{"adjacencies":[{"nodeTo":"4"},{"nodeTo":"3"}],"data":{"$color":"#EBB056","$type":"star"},"id":2,"name":"rootJuniper tree<\/label>"},
"3":{"adjacencies":[null],"data":{"$color":"#EBB056","$type":"star"},"id":3,"name":"rootPuff Bird<\/label>"},
"4":{"adjacencies":[{"nodeTo":"5"},{"nodeTo":"3"}],"data":{"$color":"#EBB056","$type":"star"},"id":4,"name":"rootJackRabbit<\/label>"},
"5":{"adjacencies":[null],"data":{"$color":"#EBB056","$type":"star"},"id":5,"name":"rootMountain Lion<\/label>"},
"6":{"adjacencies":[{"nodeTo":"1"}],"data":{"$color":"#EBB056","$type":"star"},"id":6,"name":"rootBobcat<\/label>"}} 

这是我的while循环

$previd = -1;
 while($row=$result->FetchRow())
{
$id= (float)$row['n_id']; 
$name = $row['name'];
$color1 = $row['color'];
$type1 = $row['type'];
$to= (float)$row['goingto']; 
$thumb =$row['thumb']; //image path


if ($previd != $id) {
    $previd = $id; 
    if ($previd != -1) {
        array_push($array,$node);
    }

    $node[$id] = array(
        "adjacencies" => array(),
        "data" => array(
                "$"."color" => $color1,
                "$"."type" => $type1 
            ),
        "id" => $id,
        "name" => "<img src='".$thumb."' height='25' width='25' alt='root'/><label>".$name."</label>");
}


if ($to != null) { 
    $node[$id]["adjacencies"][]=array("nodeTo" => "$to");
}


}
print_r($node);
4

2 回答 2

1

我真的不明白你为什么不使用就得到一个非常完美的 json 字符串,json_encode()但我会尽力接近你真正想要的

echo json_encode(array_values($array));

其中$array是要转换为不带索引号的 JSON 的数组

所以这意味着它会是这样的

 echo json_encode(array_values($node));

在这种情况下,您需要array_values()使用http://php.net/manual/en/function.array-values.php

于 2013-03-31T07:17:08.980 回答
0

很难有信心地说,但是呢?

for($node as $n)
{
    print_r($n);
}

或者

for($node as $k=>$n)
{
    print_r($n);
}

但实际上,print_r它更像是一种调试工具,而不是输出格式化工具。

编辑:现在我看到您对 JSON 的评论...使用 JSONjson_encode()

print(json_encode($node));

如果您仍然获得数组索引,请尝试类似

print(implode("\n", array_map("json_encode", $node)));
于 2013-03-31T07:14:25.287 回答