0

我有一个数组存储等级名称,等级值作为键,等级名称作为值:

$labels=array(1=>'Insufficient',2=>'Sufficient',3=>'Satisfactory',4=>'Good',5=>'Excellent' );

然后,还有另一个数组存储所有获得成绩的人的记录,其中 user_id 为 key,grade value 为 value:

$grades = array( 123 = > 1, 456 => 5 , 789 = > 3);

现在我想统计每个年级下的记录-- grade-1 => 5 users, grade-2=>6 users,形式如下:

array(1=>5, 2=>6, 3=>2, 4=>2, 5=>1);

我试过这个并得到未定义偏移的错误:

$result = array();

for($i=1;$i<=5;++$i)
{
    foreach($grades as $user_id=>$user_grade)
    {
        $result[$i] = ( $user_grade == $i ) ? $result[$i]+1 : $result[$i];
    }
}

如何获得计算每个年级下有多少用户的结果数组?

4

2 回答 2

3

听起来像array_count_values()会成功。

例如

<?php
$grades = array ( // this array contains no value "1"
   68 => 4, 138 => 4, 189 => 2, 255 => 4,
  297 => 3, 366 => 2, 425 => 4, 465 => 3,
  489 => 5, 580 => 4, 646 => 4, 704 => 5,
  784 => 2, 811 => 4, 897 => 4, 974 => 5,
  1006 => 2, 1093 => 2, 1189 => 2, 1222 => 4
);

$cnt = array_count_values($grades);
$cnt += array(1=>0,0,0,0,0);
ksort($cnt);

print_r($cnt);

印刷

Array
(
    [1] => 0
    [2] => 6
    [3] => 2
    [4] => 9
    [5] => 3
)
于 2012-08-21T08:55:14.517 回答
0

尝试一下 :

// $labels = array("Grade Value" => "Grade Name")
$labels=array(1=>'Insufficient',2=>'Sufficient',3=>'Satisfactory',4=>'Good',5=>'Excellent' );

// $grades = array("User Id" => "Grade Value")
$grades = array( 123 => 1, 456 => 5 , 789 => 3);

//OutPUT :  array( "Gread Value " => "No Of Users ")

foreach($labels as $key => $value)
{
    $userCount = 0;
    foreach($grades as $key1=> $value1)
    {
        if($key == $value1)
        {
            $userCount++;
        }
    }

    $result[$key] = $userCount;
}

print_r($result);
于 2012-08-21T09:50:06.047 回答