views:

166

answers:

3

I've got a multidimentional array such as:

$array = array(
  array('test'=>23, 'one'=>'etc' , 'blah'=>'blah'),
  array('test'=>123, 'one'=>'etc' , 'blah'=>'blah'),
  array('test'=>33, 'one'=>'etc' , 'blah'=>'blah'),
);

How to I search the array for all the keys 'test' and get the value? I wish to add all of the values of 'test' found in the array, so it'd come up with '214' for example. The array should be any depth but the key will be the same no matter what.

+2  A: 

Use array_walk_recursive() for this:

class Sum { public $total = 0; }
$sum = new Sum;
array_walk_recursive($array, 'add_test', $sum);

function add_test($item, $key, $sum) {
  if ($key == 'test') {
    $sum->total += $item;
  }
}

print $sum->total;

Why have the Sum object? Because otherwise you have to work out the total with a global variable, which is OK but possibly messy. Objects are passed by reference. You could use the object to control things like what key to search for or whatever too.

cletus
+5  A: 

To handle recursive arrays.

$array = array(
  array('test' => 23, 'one' => array("a" => "something", "test" => 28), 'blah' => array("test" => 21)),
  array('test' => 123, 'one' => 'etc' , 'blah' => 'blah'),
  array('test' => 33, 'one' => 'etc' , 'blah' => 'blah'),
);

function recursiveSum($array, $keyToSearch) {
    $total = 0;
    foreach($array as $key => $value) {
        if(is_array($value)) {
            $total += recursiveSum($value, $keyToSearch);
        }
        else if($key == $keyToSearch) {
            $total += $value;
        }
    }
    return $total;
}

$total = recursiveSum($array, "test");
Anurag
+1. I think you mean $total += recursiveSum(...), not $total += sumOfKeys(...)
Mike
that's what happens when we don't use tools to refactor :)
Anurag
+1  A: 
$total = 0;
function crawl( $array ) {
    global $total;

    if( is_array( $array ) ) {
        foreach( $array as $key=>$val ) {

            if( $key === "test" ) {             
                $total = $total + $val;             
            }

            crawl( $val );          
        }
    }

    return $total;  
}

Any depth.

lemon