Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How do I search an array for all entries of a specific key and return value?

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.

like image 281
Jason Avatar asked Dec 29 '22 05:12

Jason


1 Answers

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");
like image 114
Anurag Avatar answered Jan 14 '23 01:01

Anurag