0

suppose I have a multidimensional array structure:

array(parent)
    array
    array
    array(parent)
        array(parent)
            ...some key I'm looking for....
        array
    array
array
array
array
array
array

I iterate over it recursively to find an array that contains some key I'm looking for - this is no problem.

But then I need to walk up the tree and add additional key to all parents (marked by parent). I can't wrap my head around it. I can easily walk down the tree recursively but I can't figure out how to walk up. Can someone point me to the right direction?

Stann
  • 13,518
  • 19
  • 65
  • 73
  • If you have only a reference to a "child" element there is no way to derive from it its "parent" element except to iterate recursively through the entire structure until the child is reached. Perhaps you should use a tree-like data structure such as [Tree](http://pear.php.net/package/Tree) from PEAR? – Jordan Running Oct 13 '11 at 06:58
  • hmm. maybe I should indeed:) Let's see though if anyone else in community has anything to add. – Stann Oct 13 '11 at 07:06

2 Answers2

3

This is an example that I've just wrote just to get the idea.

NOTE that this will break execution on the first occurrence of the matched value.

codepad link

$arr = array(
    array('a','b','c','d'),
    array(61,62,63,64,65),
    array('e','f','g','h'),
    array(6,7,8,9),
    array(1,2,array(1,2,3,4,5,6,7,8),4,5,6,7,8),
    array('i','j','k','l','m'),
);

function array_walkup( $desired_value, array $array, array $keys=array() ) {
    if (in_array($desired_value, $array)) {
        array_push($keys, array_search($desired_value, $array));
        return $keys;
    }
    foreach($array as $key => $value) {
        if (is_array($value)) {
            $k = $keys;
            $k[] = $key;
            if ($find = array_walkup( $desired_value, $value, $k )) {
                return $find;
            }
        }
    }
    return false;
}

$keys = array_walkup(3, $arr);

echo "3 has been found in \$arr[".implode('][', $keys)."]";
Teneff
  • 30,564
  • 13
  • 72
  • 103
1

You can use something along these lines in a class:

private $valueFound;

public function recurse($item)
{
   if ($item['special_field'] === 'value you are looking for')
   {
      $this->valueFound = $item['other_field'];
      return;
   }

   if (isset($item['child'])
   {
      recurse($item['child']);
   }

   // Use tail-recursion.
   // You are at this point past all recursion and are heading back up the tree.
   $item['field_to_set'] = $this->valueFound;
}
Paul
  • 6,572
  • 2
  • 39
  • 51