我尝试从控制器而不是刀片获取循环,这是问题所在:
如果我在刀片中有这样的代码一切正常
@foreach($orders as $order)
@php
$data = json_decode($order->product_name, true)
@endphp
@php $sum = 0 @endphp
@foreach($data as $item)
@php $sum += $item['quantity'] @endphp
@endforeach
Totlal Quantity Ordered: {{$sum}}
@endforeach
但是,当我尝试将所有这些@php
@foreach
带入控制器并且只在我的刀片中获得简单{{$sum}}
时,一切都会变得混乱。并且我为所有行保持相同的值。
这是我在控制器中的当前代码:
public function index()
{
$orders = Order::orderby('id', 'desc')->paginate(10);
$allorders = Order::orderby('id', 'desc')->get();
foreach($allorders as $order){
$order;
}
$data = json_decode($order->product_name, true);
$sum = 0;
foreach($data as $item){
$sum += $item['quantity'];
}
$sum;
return view('admin.orders.index', compact('orders', 'sum'));
}
PS:我的数据保存为json,每个订单只能有
1
个产品 或其中的n
个产品。
提前感谢。
我在数据库列中的数据
{"37": {"id": 37, "name": "test product", "price": 456346, "quantity": 15, "attributes": [], "conditions": []}}
我的数据作为
之后的刀片中的数组@php
$data = json_decode($order->product_name, true)
@endphp
通过
{{dd($data)}}
array:6 [▼
15 => array:6 [▼
"id" => 15
"name" => "test product"
"price" => 157952
"quantity" => 7
"attributes" => []
"conditions" => []
]
29 => array:6 [▼
"id" => 29
"name" => "effewf"
"price" => 24524
"quantity" => 1
"attributes" => []
"conditions" => []
]
30 => array:6 [▼
"id" => 30
"name" => "efreFR"
"price" => 3434
"quantity" => 1
"attributes" => []
"conditions" => []
]
32 => array:6 [▼
"id" => 32
"name" => "product 18"
"price" => 1000000
"quantity" => 1
"attributes" => []
"conditions" => []
]
33 => array:6 [▼
"id" => 33
"name" => "tyq53y5"
"price" => 4567457
"quantity" => 2
"attributes" => []
"conditions" => []
]
37 => array:6 [▼
"id" => 37
"name" => "test product"
"price" => 456346
"quantity" => 3
"attributes" => []
"conditions" => []
]
]
答案 0 :(得分:1)
你应该在结束后关闭foreach。
试试这个
public function index()
{
$orders = Order::orderby('id', 'desc')->paginate(10);
foreach ($orders as $key => $order) {
$data = json_decode($order->product_name, true);
$sum = 0;
foreach($data as $item){
$sum += $item['quantity'];
}
$orders[$key]->sum = $sum;
}
return view('admin.orders.index', compact('orders'));
}
在刀片模板中
@foreach ($orders as $key => $value)
{{ $value['sum'] }}
@endforeach