Reputation: 27
$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));
I have some result in array like this:
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 )
how to get result as following:
score for B = 8
score for C = 2
Upvotes: 0
Views: 135
Reputation: 57690
If your sub arrays contain only 1 items, you can use following code.
array_count_values(array_map('key', $array));
Here,
array_count_values()
Counts all the values of an arrayarray_map()
Applies the callback to the elements of the given arrayskey()
Fetch a key from an arrayAs your are just looping its better you initialize $array
before the loop and then add items to it. After the loop ends invoke 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";
Upvotes: 2
Reputation: 10090
$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);
output of print_r($base)
:
Array
(
[0] => Array
(
[B] => 1
)
[1] => Array
(
[C] => 1
)
[2] => Array
(
[B] => 1
)
[3] => Array
(
[B] => 1
)
[4] => Array
(
[C] => 1
)
)
output of print_r($score)
:
Array
(
[B] => 3
[C] => 2
)
Upvotes: 0
Reputation: 12038
Here is a function that will return the sum for a particular letter:
function getTotal($key, $array) {
$total = 0;
foreach ($array as $currentArray) {
foreach ($currentArray as $currentKey => $currentValue) {
if ($key === $currentKey) {
$total += $currentValue;
}
}
}
return $total;
}
Then use it like:
$totalForB = getTotal('B', $myArray);
Upvotes: 0