views:

302

answers:

4

Hi

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]["children"] ...
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);
+1  A: 
$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 );
Elzo Valugi
+1  A: 

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'];
}
thetaiko
A: 
$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;
}
chris
A: 

(It's DinDong with another ID)

Thanks to all of you guys. I chose the solution Elzo provided. This works like a charm!

You should accept that answer then. Click the checkmark next to the answer.
chris