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
Simply, iterates through the array, accumulates the
hours
in the$sum
variable where thetaskID
is empty:Another approach achieve the same result using the
array_filter
andarray_sum
witharray_column
:array_filter
is used to filter the array based on the condition thattaskID
is empty. Then,array_column
extracts thehours
from the filtered array, andarray_sum
calculates the sum of these hours: