PHP Search array recursively and return count of index 'x'?
Is there a PHP function that lets you 开发者_StackOverflow中文版search an array recursively and return the number of instances a certain key 'x' occurs (regardless of how deep)?
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;
}
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");
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.
Nope. Write your own! Recursion is fun! =D
精彩评论