php - get elements sum from array Laravel
i have an array that contains another array and i wanna get specifics elements sum
Array
array:1 [?�?
0 => array:3 [?�?
"shop_id" => 1
"delegate_id" => 2
"items" => array:3 [?�?
0 => array:3 [?�?
"product_id" => 2
"price" => 4.75
"quantity" => 1
]
1 => array:3 [?�?
"product_id" => 6
"price" => 18.5
"quantity" => 1
]
2 => array:3 [?�?
"product_id" => 10
"price" => 88
"quantity" => 2
]
]
]
]
i need to get the sum of price
any ideas to do this?
Answer
Solution:
If there is relationships there is a better approach. As the data you have given you could call sum twice and make it work.
collect($array)->sum(function (array $shop) {
return collect($shop['items'])->sum('price');
});
This will sum each individual shop and the sum amount would be the sum of each shops items.
Source