2009-07-02 55 views
2

我想遞歸搜索和替換數組中的元素。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。

回答

8

把你的代碼放到一個函數並再次調用它。僞代碼:

function checkArray($array) { 
    ... 
    if (is_array($node)) { // or whatever other criterium 
     checkArray($node); // same function 
    } 
} 

遞歸的基礎是再次調用相同的代碼...

2

您需要將此代碼添加到函數中並調用子節點上的函數。

像這樣(注意parseNodes函數的函數內部再次調用):

function parseNodes($node) { 

    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'] = parseNodes($this->site->get_descendants($node['lft'], $node['rgt'])); 
    } 
    } 
    return $nodes; 
} 

喬希

+0

如果子節點沒有返回任何內容,則需要在該函數上添加某種檢查,否則將會陷入循環 – Josh 2009-07-02 12:49:11

0

這裏有一個遞歸解決方案

function makeObject($array){ 
    $data = false; 
    foreach($array as $key=>$value){ 
     if(is_array($value)){ 
     $value = makeObject($value); 
     } 
     $data -> {$key} = $value; 
    } 
    return $data; 
} 

感謝讓我有!