簡體   English   中英

php中多維數組的計數值

[英]Count value in multidimensional array in 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] => 
        )

這是一個簡單的解決方案。 這不是最好的,因為它是一些可以通過使用 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM