My $results array looks like this..
$results = [
'2020-09-06' => [
'Etsy' => ['total_orders' => 2, 'total_stickers' => 3, 'total_value' => 7.8300000000000001],
'Woo' => ['total_orders' => 10, 'total_stickers' => 20, 'total_value' => 100.38],
'eBay' => ['total_orders' => 17, 'total_stickers' => 18, 'total_value' => 67.359999999999999],
],
'2020-09-07' => [
'Etsy' => ['total_stickers' => 8, 'total_orders' => 4, 'total_value' => 34.920000000000002],
'Woo' => ['total_stickers' => 9, 'total_orders' => 3, 'total_value' => '52.90'],
'eBay' => ['total_stickers' => 23, 'total_orders' => 21, 'total_value' => 58.030000000000001],
]
];
I want to echo the combined sum for each individual item (total_value, total_stickers, total_orders) for each "marketplace" by date and thought i could do this if i pass the variables in a function and tried the following..
$array_value_sum = create_function('$array,$key', '$total = 0; foreach($array as $row) $total = $total + $row[$key]; return $total;');
echo "Total Current Value" . $array_value_sum($obj['results'], 'total_value');
That way I can change the variables and sum any of them with a similar echo line but this is not working for me, do I also need to specify dates in a foreach? or how can I achieve this expected output..
Array
(
[2020-09-06] => Array
(
[total_orders] => 29
[total_stickers] => 41
[total_value] => 175.5
)
[2020-09-07] => Array
(
[total_stickers] => 40
[total_orders] => 28
[total_value] => 145.85
)
)
2
Answers
One way would be to simply loop over it with a couple of foreach’s and add the values together.
Sum all by date, including all marketplaces.
Result:
https://3v4l.org/qQ04D
Original answer: Sum all marketplaces.
Result:
https://3v4l.org/g4CmZ
As always, no need to over-engineer, if you know the structure, just iterate trough the values, and sum them up, this is how I would do that.
This way you can add many other marketplace and dates without later modifying the code.