Reputation: 1899
I have the result from database.
Array
(
[0] = stdClass Object
(
[name] = First
[sum] = 3,8,...
)
[1] = stdClass Object
(
[name] = Second
[sum] = -1,0,...
)
[2] = stdClass Object
(
[name] = Third
[sum] = 2,-1...
)
)
So now I need to sum all in column "sum".
I need to get result like
$final = (4, 7,...);
I have transformed sum to array throw explode() and then tried with foreach
for example
foreach ($result as $k=>$subArray) {
$arrayNumbers = explode(",",$subArray->sum);
foreach ($arrayNumbers as $key => $value) {
$sumArray[] = $value];
$stepToSum2[] = array_sum($sumArray);
}
unset($arrayNumb);
}
Not sure that my example working because I'm already stuck with commented code.
Anyway, I with some manipulations I can get or sum right for the first numbers (5) or the sum of my array (11).
The same result with this
$sum = array_sum(array_map(function($var) {
return $var['sum'];
}, $myResultArray));
I have searched for the answer but most of the answers only for two arrays, but in same tables, I have more than 5 arrays, so I can't figure out how to implement this.
Upvotes: 2
Views: 130
Reputation: 41810
array_reduce
is good for reducing an array to a single value as you're doing here. It takes an array and a function that updates a "carry" value for each item in your array.
$result = array_reduce($your_array, function($carry, $item) {
foreach (explode(',', $item->sum) as $key => $value) {
$carry[$key] = $value + (isset($carry[$key]) ? $carry[$key] : 0);
// (OR $carry[$key] = $value + ($carry[$key] ?? 0); in PHP 7)
}
return $carry;
}, []);
Upvotes: 4
Reputation: 78994
Since you're already creating an array:
foreach ($result as $subArray) {
$arrayNumbers[] = explode(",", $subArray->sum);
}
$first = array_sum(array_column($arrayNumbers, 0));
$second = array_sum(array_column($arrayNumbers, 1));
Upvotes: 1
Reputation: 924
Try this :
foreach ($result as $k => $subArray) {
$arrayNumbers = explode(",",$subArray->sum);
foreach ($arrayNumbers as $key => $value) {
$sumArray[$key] = isset($sumArray[$key]) ? $sumArray[$key] : 0;
$sumArray[$key] += $value;
}
}
print_r($sumArray);
Upvotes: 0