避免打印数组的索引?

时间:2013-03-31 07:07:25

标签: php

我正在循环遍历多维/嵌套数组,我得到以下结果,但是我想摆脱每个数组前面的“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);

2 个答案:

答案 0 :(得分:1)

我真的不明白你怎么会在不使用json_encode()的情况下得到一个非常完美的json字符串,但我会尽力接近你真正想要的东西

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

答案 1 :(得分:0)

很难自信地说,但是

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

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

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

修改:现在我看到您对JSON的评论了...... use JSONjson_encode()

print(json_encode($node));

如果你仍然使用它获得数组索引,请尝试类似

的内容
print(implode("\n", array_map("json_encode", $node)));