如果您嘗試以下代碼,該怎麼辦?請注意,在不改變遞歸內源數組的情況下,必須有更好的方法。
$array = array(
1 => array(
2 => 2,
4 => 4
),
2 => array(
3 => 3
),
3 => array(
5 => 5
),
9 => array(
6 => 6
)
);
//we need the copy to delete there nodes that have been re-atached. Otherwise, we end up changing the array itself within recursion, which is not good
$arrayCopy = $array;
function recursive(&$array, &$arrayCopy) {
foreach($array as $key => &$value) {
//if we found the leaf node
if(!is_array($value)) {
// and there is something in the array copy with this index
if(array_key_exists($key, $arrayCopy)) {
// re-attach it to the initial array. $value is passed by reference. BTW, not a good approach as I stated above, but it works on the sample data
$value = $arrayCopy[$key];
// remove that node from array copy in order to not double process it.
unset($arrayCopy[$key]);
// call it again for the leaf-node value
recursive($value, $arrayCopy);
}
// here is recursion exit, if we don't find anything in the arracy copy for the fiven leaf node
} else {
//recursive call it for the node
recursive($value, $arrayCopy);
}
}
}
// launch the recursion
recursive($array, $arrayCopy);
// now we need to remove the nodes that have been removed from the array copy, i.e. the ones being re-attached. We could not do this in the recursion
$result = array();
foreach(array_keys($arrayCopy) as $initial_key) {
$result[$initial_key] = $array[$initial_key];
}
var_dump($result);
如果第一個數組包含一個鍵'5',則輸出數組應該更深一層,我正確嗎?如果是這種情況,您需要搜索遞歸。 :-) – Blaatpraat
不完全是,這些數字只是與結構相關,這些數字將永遠不會相同。數組鍵是parent_id,值是兒童列表,我想將所有父母和孩子用相同的ID – aranna