PHP. to approach a multidimensional array?

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 it recursively to find an array containing some key that I am looking for - no problem.

But then I need to go to the tree and add an extra key to all the parents (marked by the parent). I can't get my head around me. I can easily walk down the tree recursively, but I can't figure out how to approach. Can anyone point me in the right direction?

0


source to share


2 answers


This is an example I just wrote to get this idea.

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



code page 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)."]";

      

+3


source


You can use something along these lines in the 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;
}

      

+1


source







All Articles