开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜