I have one JSON like:
[
{
"id": 1,
"order_id": 1,
"product_id": 2,
"quantity": "15.00",
"created_at": "2019-03-19 10:02:40",
"products": [
{
"id": 2,
"name": "24 mantra",
"sale_price": "45.00"
}
]
},
{
"id": 3,
"order_id": 2,
"product_id": 2,
"quantity": "15.00",
"created_at": "2019-03-19 10:16:15",
"products": [
{
"id": 2,
"name": "24 mantra",
"sale_price": "45.00"
}
]
},
{
"id": 5,
"order_id": 3,
"product_id": 2,
"quantity": "15.00",
"created_at": "2019-03-19 10:16:19",
"products": [
{
"id": 2,
"name": "24 mantra",
"sale_price": "45.00"
}
]
},
{
"id": 2,
"order_id": 1,
"product_id": 3,
"quantity": "3.00",
"created_at": "2019-03-19 10:02:40",
"products": [
{
"id": 3,
"name": "24 Mantra Jowar Atta 2LB",
"sale_price": "45.00"
}
]
},
{
"id": 4,
"order_id": 2,
"product_id": 3,
"quantity": "3.00",
"created_at": "2019-03-19 10:16:16",
"products": [
{
"id": 3,
"name": "24 Mantra Jowar Atta 2LB",
"sale_price": "45.00"
}
]
}
]
now I want to calculate total sale as quantity multiply by product of sale_price
of every object and sum of quantity * sale_price
per product.
expected output
[
{
"product": "24 mantra",
"sale": 2025
},
{
"product": "24 Mantra Jowar Atta 2LB",
"sale": 270
}
]
code for output
$orderlines = OrderLine->with('products:id,name,sale_price')->select('id','order_id','product_id','quantity','created_at')->get();
$orderlines = $orderlines->groupBy('product_id');
$totalproductsale = [];
foreach($orderlines as $key => $singleline) {
$total_bysales = 0.00;
foreach($singleline as $singleproduct) {
$total_bysales += $singleproduct->quantity * $singleproduct->sale_price;
}
array_push($totalproductsale,array("product" => $singleline['0']->products['0']->name,"totalsale" => number_format($total_bysales, 2, '.', '')));
$totalsale[$key] = number_format($total_bysales, 2, '.', '');
}
I want to get total sale and product name into one object, for that I have used a foreach
loop but it's very time consuming, I have 100 000 data into production server. It takes 15 sec to load only 30k data into chart. how can I reduce the time of iteration or use any other alternatives?
You can try this, the json you must take it to the controller. I pasted the json directly
$json = '[ { "id": 1, "order_id": 1, "product_id": 2, ... ]';
$array = json_decode($json, true);
$collection = collect($array);
Then you can manipulate the data easily with a collection