PHP递归搜索和替换数组元素 [英] PHP recursive search and replace array elements

查看:138
本文介绍了PHP递归搜索和替换数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要递归搜索,并在一个阵列替换元素。

I want to recursively search and replace elements in an array.

该阵列是基于树,以便看起来像

The array is tree based so looks like

Object
   Children
      Object type A
      Object type B
Object
   Children
      Object type A
Object

等。

我希望能够与其他物品来代替某些项目,因此,例如,我想更换阵列中的所有条目(在任何深度级别)A型与B型的数组,但这里的渔获:新更换的对象还可以具有需要被替换A型的儿童

I want to be able to replace certain items with other items, so for example, I want to replace all entries in the array (at whatever depth level) of type A with an array of type B. But here's the catch: The newly replaced objects may also have children of type A that need to be replaced.

到目前为止,我已经得到了

So far I've got

    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的第一级,但不会查询的随后加入儿童

Which will replace the first level of RefObjects, but will not search the subsequently added children.

我一直在抨击我的头靠在墙上用这一个小时。请帮助!

I've been bashing my head against a wall with this one for hours. Please help!

干杯,
暖气。

Cheers, Gaz.

推荐答案

把你的code到函数并再次调用它。伪code:

Put your code into a function and call it again. Pseudocode:

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

递归的基础是调用同样的code再...

The basics of recursion are to call the same code again...

这篇关于PHP递归搜索和替换数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆