开发者

Dynamic array key in while loop

开发者 https://www.devze.com 2022-12-20 09:03 出处:网络
I\'m trying to get this working: I have an array that gets \"deeper\" every loop. I need to add a new array to the deepest \"children\" key there is.

I'm trying to get this working:

I have an array that gets "deeper" every loop. I need to add a new array to the deepest "children" key there is.

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

So, in a loop it would be:

array_push($json["children"] ...
array_push($json["children"][0]["ch开发者_如何学运维ildren"] ...
array_push($json["children"][0]["children"][0]["children"] ...

... and so on. Any idea on how to get the key-selector dynamic like this?

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


$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 );


Hmmm - maybe better to assign by reference:

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


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

If you want to read an array via a string path, split the string in indices, and then you can do something like this to get the value

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

精彩评论

暂无评论...
验证码 换一张
取 消