我想遞歸搜索和替換數組中的元素。PHP遞歸搜索和替換數組元素
該陣列是基於樹,以便看起來像
Object
Children
Object type A
Object type B
Object
Children
Object type A
Object
等
我希望能夠與其他物品來代替某些項目,因此,例如,我想替換所有條目數組(在任何深度級別)類型A與數組類型B.但這裏是catch:新替換的對象也可能有需要被替換的類型A的子項。
到目前爲止,我已經得到了
foreach($nodes as &$node) {
// Replace node?
if($node['type'] == 'RefObject') {
$n = $this->site->get_node_where('id', $node['node_ref']);
// Replace node
$node = $this->site->get_node_where('object_id', $n['object_id']);
// Get children
$node['children'] = $this->site->get_descendants($node['lft'], $node['rgt']);
}
}
return $nodes;
將取代RefObjects的第一級,但不會搜索隨後加入的孩子。
我一直在用這個小時抨擊我的頭撞牆。請幫忙!
乾杯, Gaz。
如果子節點沒有返回任何內容,則需要在該函數上添加某種檢查,否則將會陷入循環 – Josh 2009-07-02 12:49:11