array count()问题

时间:2012-12-25 08:43:40

标签: php

$nialiakhirpraktikum = $ntugasakhir+$ratarata; //from other process 
if ($nialiakhirpraktikum>79) { $grade="A"; } 
else if ($nialiakhirpraktikum<=79 AND $nialiakhirpraktikum>67) { $grade="B"; } 
else if ($nialiakhirpraktikum<=67 AND $nialiakhirpraktikum>55) { $grade="C"; } 
else if ($nialiakhirpraktikum<=55 AND $nialiakhirpraktikum>44) { $grade="D"; } 
else { $grade="E"; }     
$array = array($grade); 
print_r(array_count_values($array));

我有一些像这样的数组结果:

Array ( [B] => 1 ) 
Array ( [B] => 1 ) 
Array ( [C] => 1 ) 
Array ( [C] => 1 ) 
Array ( [B] => 1 ) 
Array ( [B] => 1 ) 
Array ( [B] => 1 ) 
Array ( [B] => 1 ) 
Array ( [B] => 1 ) 
Array ( [B] => 1 )

如何获得如下结果:

score for B = 8

score for C = 2

3 个答案:

答案 0 :(得分:2)

如果子数组只包含1个项目,则可以使用以下代码。

array_count_values(array_map('key', $array));

下面,

Ideone

更新

由于您只是循环更好,因此在循环之前初始化$array,然后向其中添加项目。循环结束后调用array_count_values

$array = array(); // initialize before loop
for(...){   /// sample loop
   // your original code
   $array[] = $grade;  // add grades here
}
$grade_distribution = array_count_values($array); // count it

foreach($grade_distribution as $g => $count)
    echo "score for $g = $count\n";

答案 1 :(得分:0)

这是一个函数,它将返回特定字母的总和:

function getTotal($key, $array) {
    $total = 0;
    foreach ($array as $currentArray) {
        foreach ($currentArray as $currentKey => $currentValue) {
            if ($key === $currentKey) {
                $total += $currentValue;
            }
        }
    }
    return $total;
}

然后使用它:

$totalForB = getTotal('B', $myArray);

答案 2 :(得分:0)

$base=array(array("B"=>1),array("C"=>1),array("B"=>1),array("B"=>1),array("C"=>1));
print_r($base); // just to debug
$score=array_reduce($base,function(&$rst,$i){
    foreach($i as $k=>$s){
        if(empty($rst[$k])){
            $rst[$k]=0;
        }
        $rst[$k]+=$s;
    }
    return $rst;
},array());
print_r($score);

print_r($base)的输出:

Array
(
    [0] => Array
        (
            [B] => 1
        )

    [1] => Array
        (
            [C] => 1
        )

    [2] => Array
        (
            [B] => 1
        )

    [3] => Array
        (
            [B] => 1
        )

    [4] => Array
        (
            [C] => 1
        )

)

print_r($score)的输出:

Array
(
    [B] => 3
    [C] => 2
)