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?

2
  • 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 from PEAR? Commented Oct 13, 2011 at 6:58
  • hmm. maybe I should indeed:) Let's see though if anyone else in community has anything to add. Commented Oct 13, 2011 at 7:06

2 Answers 2

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)."]";
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.