katie hudson
katie hudson

Reputation: 2893

Count number of elements within Objects

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

Upvotes: 0

Views: 66

Answers (1)

Ulrik McArdle
Ulrik McArdle

Reputation: 654

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

Upvotes: 3

Related Questions