首页 > 解决方案 > 在php中计算多维数组中的值

问题描述

您好,我想计算多维数组中的每个键值,我想要类似的结果

[Computer] => 1
[mathematics] =>2
[drawing] => 3 

我尝试了以下代码

$count = call_user_func_array('array_merge_recursive', $Array);

这是我的数组

Array
(
    [0] => Array
        (
            [StudentName] => Test 1 
            [Drawing] => 50.00
            [Mathematics] => 40.00
            [Computer] => 
        )

    [1] => Array
        (
            [StudentName] => Test 2  
            [Mathematics] => 
            [Computer] => 80.00
        )

    [2] => Array
        (
            [StudentName] => Test 3
            [Drawing] => 80.00
            [Mathematics] => 95.00
            [Computer] => 
        )

标签: phparrays

解决方案


这是一个简单的解决方案。这不是最好的,因为您可以通过使用 php 提供的一些数组函数来减少一些行。

$newArr = [];
foreach($Array as $group) {
    foreach($group as $key => $value) {
        if(!empty($value)) {
            $newArr[$key] = isset($newArr[$key]) ? $newArr[$key]+1 : 1;
        } else {
            if(!isset($newArr[$key])) {
                $newArr[$key] = 0;
            }
        }
    }
}

var_dump($newArr);

推荐阅读