while循环中的动态数组键

时间:2010-02-18 15:08:59

标签: php multidimensional-array

我正在尝试让这个工作:

我有一个数组,每个循环都会“更深入”。我需要在最深的“children”键中添加一个新数组。

while($row = mysql_fetch_assoc($res)) {
    array_push($json["children"],
                        array(
                            "id" => "$x",
                            "name" => "Start",
                            "children" => array()
                        )
                    );
}

所以,在一个循环中它将是:

array_push($json["children"] ...
array_push($json["children"][0]["children"] ...
array_push($json["children"][0]["children"][0]["children"] ...

......等等。关于如何让键选择器像这样动态的任何想法?

$selector = "[children][0][children][0][children]";
array_push($json$selector);

3 个答案:

答案 0 :(得分:3)

$json = array();
$x = $json['children'];
while($row = mysql_fetch_assoc($res)) {
    array_push($x,
                array(
                    "id" => "$x",
                    "name" => "Start",
                    "children" => array()
                )
            );
    $x = $x[0]['children'];
}
print_r( $json );

答案 1 :(得分:1)

嗯 - 也许最好通过引用分配:

$children =& $json["children"];
while($row = mysql_fetch_assoc($res)) {
    array_push($children,
        array(
            "id" => "$x",
            "name" => "Start",
            "children" => array()
        )
    );
    $children =& $children[0]['children'];
}

答案 2 :(得分:0)

$json = array();
$rows = range('a', 'c');
foreach (array_reverse($rows) as $x) {
    $json = array('id' => $x, 'name' => 'start', 'children' => array($json));
}
print_r($json);

如果你想通过一个字符串路径读取一个数组,在索引中拆分字符串,然后你可以做这样的事情来获得值

function f($arr, $indices) {
    foreach ($indices as $key) {
        if (!isset($arr[$key])) {
            return null;
        }
        $arr = $arr[$key];
    }
    return $arr;
}