多个Foreach循环 - Laravel

时间:2017-04-03 11:48:39

标签: php laravel

我正在尝试将2个foreach循环结果合并到1个表中。附图。 enter image description here

第1栏产品:

$products=[{"product_name_id":"pro_des_5","quantity":180},{"product_name_id":"pro_des_6","quantity":240},{"product_name_id":"pro_des_7","quantity":156}];

休息数据:

$summary=[{"ptotal":1,"month":"March","product_id":"pro_des_7"},{"ptotal":3,"month":"April","product_id":"pro_des_5"},{"ptotal":2,"month":"April","product_id":"pro_des_6"},{"ptotal":12,"month":"April","product_id":"pro_des_7"}];

对于每个产品,每月消费量我想在每个月的行中添加从$ summary获取数据,但无法合并两个foreach循环?任何建议。

<tbody>
@foreach($products as $product)
<tr>
<td>{{$product->product_name_id}}</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
@endforeach
</tbody>

1 个答案:

答案 0 :(得分:0)

创建一个新数组,结构如下:

$array = [
   ["product_name_id" => "pro_des_5" , "jan" => 3, "feb" => 0 , ..etc ]
];

您将通过循环$arrayColumn1 Products来填充Rest data

foreach($products as $product) {
  foreach($summary as $summary) {
     $value = 0;
    if ($summary->product_id == $product->product_name_id)
       // do the sum here also push to the new $array
       $value = ? // the sum you need
  }
  $array[] = ["product_name_id" => $product->product_name_id, $summary->month => $value ]
}

然后你可以这样做:

<tbody>
@foreach($array as $product)
<tr>
<td>{{$product->product_name_id}}</td>
<td>{{$product->jan}}</td>
<td>{{$product->feb}}</td>
..
..
</tr>
@endforeach
</tbody>