没有for循环的laravel操作数组,可提供更好的性能和优化

时间:2019-03-19 13:18:27

标签: laravel loops optimization eloquent

我有一个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秒。如何减少迭代时间或使用其他替代方法?

2 个答案:

答案 0 :(得分:0)

使用collect帮助程序转换集合中的数组,并对其进行操作。只需几行代码,有很多辅助函数可以实现您想要的目标。

答案 1 :(得分:0)

您可以尝试一下,必须将json传送到控制器。我直接粘贴了json

$json = '[ { "id": 1, "order_id": 1, "product_id": 2, ... ]';
$array = json_decode($json, true);
$collection = collect($array);

然后,您可以通过集合轻松地操作数据

enter image description here