1

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

3 Answers 3

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 );
Sign up to request clarification or add additional context in comments.

Comments

1

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'];
}

Comments

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

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.