我有一个提交模型并使用查询,我得到所有提交的列表。然后,为了进入每个提交,我使用循环
foreach ($submissions as $submission) {
}
每次提交都有以下要素
[original:protected] => Array
(
[id] => 1
[sessionKey] => dfshduifhsduifhsdiu
[number] => 9
[isCompleted] => 0
[created_at] => 2017-07-29 23:14:02
[updated_at] => 2017-07-30 00:04:00
)
我要做的是生成一个数组,输出有关所有提交的一些细节。我需要的第一件事是提交的总数。接下来我需要完整(isComplete = 1)和不完整(isComplete = 0)记录的数量。为了实现这一目标,我正在做
function submissionSummary($submissions) {
$reportArray = array();
$totalCount = 0;
$incompleteCount = 0;
$completeCount = 0;
foreach ($submissions as $submission) {
$totalCount += count($submission);
$reportArray["total"] = $totalCount;
if($submission['isCompleted'] === "0") {
$incompleteCount += count($submission);
$reportArray["incomplete_count"] = $incompleteCount;
} elseif ($submission['isCompleted'] === "1") {
$completeCount += count($submission);
$reportArray["complete_count"] = $completeCount;
}
}
return $reportArray;
}
我不确定是否有更有效的方法可以做到这一点?
现在,我正在努力的部分是数字元素。这个数字可以是1到9之间的任何数字。我要做的是计算每个数字的数量。所以我想看看有多少提交有一个数字元素1,有多少有2个等等。我想到的唯一方法是通过很多if语句,如果可能的话我想避免。
关于我如何能够正确地理解这一点的任何建议。
由于
答案 0 :(得分:3)
简单的方法就是放弃foreach而只是这样做:
function submissionSummary($submissions){
$report = []; // or array() if you prefer
$report['completeCount'] = $submissions->where('isCompleted', 1)->count();
$report['inCompleteCount'] = $submissions->where('isCompleted', 0)->count();
$report['totalCount'] = $submissions->count();
return $report;
}