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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With