我有一个JSON,如:
[
{
"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"
}
]
}
]
现在,我想将总销售量计算为数量乘以每个对象的sale_price
乘积和每个产品quantity * sale_price
的总和。
预期输出
[
{
"product": "24 mantra",
"sale": 2025
},
{
"product": "24 Mantra Jowar Atta 2LB",
"sale": 270
}
]
输出代码
$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, '.', '');
}
我想将销售总额和产品名称归为一个对象,因为我使用了foreach
循环,但是这非常耗时,我将10万个数据输入到生产服务器中。仅将30k数据加载到图表中需要15秒。如何减少迭代时间或使用其他替代方法?