首页 > PHP多维数组中统计元素个数

PHP多维数组中统计元素个数

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [id] => 12
                            [name] => '1'
                        )

                    [1] => Array
                        (
                            [id] => 28
                            [name] => '2'
                        )
                        .....
                )
            [1] => Array
                (
                    [0] => Array
                        (
                            [id] => 121
                            [name] => '2'
                        )

                    [1] => Array
                        (
                            [id] => 281
                            [name] => '4'
                        )
                        ...
                )
        )
        ....
 )

我想统计name对应的值出现的次数,
比如name='2'出现的次数是2
比如name='4'出现的次数是1

有什么好的办法么?

只能使用遍历的话,如何效率最高?

可以使用外部工具:mysql,Memcache、redis。



$result = array();

array_walk_recursive($demo, function($value,$key) use(&$result){
     if ($key == 'name') {
         $result[$value] += 1;
     }
});

print_r($result);

不知道能不能满足你的需求。最终的数组中的key==name的值


首先,比较中意楼上的方法
其次,这个本身也可以通过递归函数的方式来实现

function doFind(array $demo, &$result) {
    foreach ($demo as $key => $value) {
        if (is_array($value)) {
            doFind($value, $result);
        }
        if ($key == 'name') {
            if (!isset($result[$value])) {
                $result[$value] = 1;
            } else {
                $result[$value]++;
            }
        }
    }
}

$ret = [];
doFind($demo, $ret);
var_dump($ret);
通过对数组进行递归判断,进行值统计。
【热门文章】
【热门文章】