2009-07-02 42 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; 
} 

感谢让我有!