2010-02-18 3 views
1

Я пытаюсь получить эту работу:Динамический ключ массива во время цикла

У меня есть массив, который получает «глубже» каждый цикл. Мне нужно добавить новый массив к самому глубокому «дочернему» ключу.

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; 
} 
Смежные вопросы