在代码下方给出了缺席者和现在的输出总数。但我的要求是,每个分支都有一些缺席者和现在。
我希望输出如下:
cse-a: presnties:5 ;absenties:4
Cse-g:presenties:4 ;absenties:3
以下是我的代码:
<?php
$present = 0;
$absent = 0;
$students = array(array('CSE-A'=>'PRESENT'),array('CSE-A'=>'PRESENT'),array('CSE-G'=>'ABSENT'),array('CSE- G'=>'ABSENT'),array('CSE- A'=>'ABSENSENT'),array('CSE- G'=>'PRESENT'),array('CSE-G'=>'PRESENT'));//Sampled Array
foreach($students as $key=>$array)
{
foreach($array as $k=>$v)
{
if($array[$k] === 'PRESENT')
{
$present++;
}
else if ($array[$k] === 'ABSENT')
{
$absent++;
}
}
}
echo "Present Totals: ".$present.PHP_EOL;
echo "Absent Totals: ".$absent;
答案 0 :(得分:0)
试试此代码
$students = [
['CSE-A'=>'PRESENT'],
['CSE-A'=>'PRESENT'],
['CSE-G'=>'ABSENT'],
['CSE-G'=>'ABSENT'],
['CSE-A'=>'ABSENSENT'],
['CSE-G'=>'PRESENT'],
['CSE-G'=>'PRESENT'],
];
$outputs = [];
foreach ($students as $array) {
foreach ($array as $key => $value) {
if (!isset($outputs[$key])) {
$outputs[$key] = [
'present' => 0,
'absent' => 0,
];
}
//check value
if($array[$key] === 'PRESENT') {
$outputs[$key]['present']++;
} else if($array[$key] === 'ABSENT') {
$outputs[$key]['absent']++;
}
}
}
foreach ($outputs as $key => $value) {
echo $key."\n";
echo "Present Totals: ".$value['present']."\n";
echo "Present Totals: ".$value['absent']."\n";
echo "--------------\n";
}