dkruchok - 10 months ago 73

MySQL Question

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 colomn

I need to get result like

`$final = (4, 7,...);`

I have transformed

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.

Thanks.

Answer Source

`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;
}, []);
```