skip to Main Content

How can I conditionally sum elements from this multidimensional array?

From this array, I would to sum items only if taskID is empty.

Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [taskID] => 
                    [hours] => 1
                )
            [1] => Array
                (
                    [taskID] => 12345
                    [hours] => 1
                )
            [2] => Array
                (
                    [taskID] => 
                    [hours] => 2
                )
        )
)

What I have tried so far:

array_sum(array_column($datas, 'hours'));

But I do not know how to add the conditional thing.

Desired result: 3

2

Answers


  1. Simply, iterates through the array, accumulates the hours in the $sum variable where the taskID is empty:

    <?php
    $array = array(
        'data' => array(
            array(
                'taskID' => '',
                'hours' => 1
            ),
            array(
                'taskID' => 12345,
                'hours' => 1
            ),
            array(
                'taskID' => '',
                'hours' => 2
            )
        )
    );
    $sum = 0;
    foreach ($array['data'] as $item) {
        if ($item['taskID'] === '') {
            $sum += $item['hours'];
        }
    }
    
    echo "The sum of hours where taskID is empty is: " . $sum; //The sum of hours where taskID is empty is: 3
    
    ?>
    
    Login or Signup to reply.
  2. Another approach achieve the same result using the array_filter and array_sum with array_column:

    array_filter is used to filter the array based on the condition that taskID is empty. Then, array_column extracts the hours from the filtered array, and array_sum calculates the sum of these hours:

    $filteredArray = array_filter($array['data'], function($item) {
        return $item['taskID'] === '';
    });
    
    $sum = array_sum(array_column($filteredArray, 'hours'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search