dri8163 2017-08-01 22:22
浏览 45
已采纳

计算对象中的元素数量

I have a Submission Model and using a query, I get a list of all Submissions. Then in order to get into each submission, I use a loop

foreach ($submissions as $submission) {

}

Each submission has the following elements

[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
)

What I am trying to do is produce an array which outputs some details about all of the submissions. First thing I need is the total number of submissions. Next I need the number of complete (isComplete = 1) and incomplete (isComplete = 0) records. In order to achieve this, I am doing

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;
}

I am not sure if there is a more effecient way of doing this?

Now the part I am struggling with is the number element. This number can be anything from 1 - 9. What I am trying to do is count the number of each number. So I want to see how many submissions have a number element 1, how many have 2 etc. The only way I can think of to achieve this is through a lot of if statements, which if possible I would like to avoid.

Any advice on how I can structure this properly appreciated.

Thanks

  • 写回答

1条回答 默认 最新

  • doukuibi9631 2017-08-01 22:37
    关注

    The easy way is to drop the foreach and just do:

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度