PHP recursive search and replace array elements

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
    }
}

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


you need to add this code into a function and call the function on the child nodes.

something like this (note the parseNodes function is called again inside the function):

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;
 }

Josh


PHP 5.3 gets an array_replace_recursive method.

I just hope you'll be able to use it ;)

http://www.php.net/manual/fr/function.array-replace-recursive.php


A working recursive function example here:

function multidimensionalArrayScan($arr, $pattern, &$result = []) : Array
    {

        foreach ($arr as $key => $value) {

            if (is_array($arr[$key])) {
                multidimensionalArrayScan($arr[$key], $pattern, $result);
                continue;
            }

            $match  = preg_match($pattern, $value);
            if (!empty($match))
                $result[$key] = $value;
        }

        return $result;
    }