Is there a PHP function that lets you search an array recursively and return the number of instances a certain key 'x' occurs (regardless of how deep)?
I agree about recursion. :p
Pikrass
2010-01-18 21:06:55
A:
This is pretty much what the array_count_values function is for, but if you're using a multi-dimensional array as you imply, if would be fairly trivial to put something together using the array_walk_recursive function.
middaparka
2010-01-18 21:04:43
I mean in theory you could use it together with `array_keys` but as every key only occurs one time... ;-D
Felix Kling
2010-01-18 21:12:00
+5
A:
Now yes. :)
function count_key($array, $key) {
$count = 0;
foreach($array as $k => $val) {
if($k == $key)
$count++;
if(is_array($val))
$count += count_key($val, $key);
}
return $count;
}
Pikrass
2010-01-18 21:05:12
A:
This could help you.
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");
streetparade
2010-01-18 21:08:31
Not totally correct, `else if` should be only `if`. Otherwise `$foo[$key] = array()` would not be taken into account.
Felix Kling
2010-01-18 21:10:16
And why do you add the value of an element of the array to the counter?...
Felix Kling
2010-01-18 21:17:14
@Felix to return the summ of the array items like $a = array("test" =>1,array("test"=>2));$total = recursiveSum($array, "test");would return 3
streetparade
2010-01-18 21:22:45
Yes but the OP asked for a function that **counts** the number of **occurrences** of a certain key, not the sum of the values of that key.
Felix Kling
2010-01-18 21:29:06