PHP递归搜索和替换数组元素

Gaz*_*Gaz 2 php arrays recursion

我想以递归方式搜索和替换数组中的元素.

该数组是基于树的所以看起来像

Object
   Children
      Object type A
      Object type B
Object
   Children
      Object type A
Object
Run Code Online (Sandbox Code Playgroud)

等等

我希望能够用其他项替换某些项,所以例如,我想用类型B的数组替换类型A的数组(在任何深度级别)中的所有条目.但是这里是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;
Run Code Online (Sandbox Code Playgroud)

这将取代第一级RefObject,但不会搜索随后添加的子级.

我一直用这个砸我的头撞墙几个小时.请帮忙!

干杯,加兹.

dec*_*eze 8

将代码放入函数中并再次调用它.伪代码:

function checkArray($array) {
    ...
    if (is_array($node)) {  // or whatever other criterium
        checkArray($node);  // same function
    }
}
Run Code Online (Sandbox Code Playgroud)

递归的基础是再次调用相同的代码......