2010-02-18 38 views
1

我試圖讓這個工作:while while循環中的動態數組鍵

我有一個數組,每個循環獲得「更深」。我需要添加一個新的數組到最深的「子」鍵。

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

嗯 - 也許更好通過引用來分配:

$children =& $json["children"]; 
while($row = mysql_fetch_assoc($res)) { 
    array_push($children, 
     array(
      "id" => "$x", 
      "name" => "Start", 
      "children" => array() 
     ) 
    ); 
    $children =& $children[0]['children']; 
} 
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; 
}