您好我无法正确显示MySQL的JSON数据,我需要单独访问JSON中每个项目的'SKU'和'qty'键。我的代码如下所示:
// dummy data save
$order_items = array();
for ($i = 0; $i < 5; $i++) {
array_push($order_items, array('SKU' => $item_sku, 'qty' => 1));
}
$order->items = $order_items;
$order->user_id = Auth::id();
$order->save();
// 'items' field in MySQL
[{"SKU": "CM10361", "qty": 1}, {"SKU": "CM10361", "qty": 1}, {"SKU": "CM10361", "qty": 1}, {"SKU": "CM10361", "qty": 1}, {"SKU": "CM10361", "qty": 1}]
// controller
$orders = Order::with('orderAuthor')->orderBy('id', 'desc')->get();
// blade view code
{{ json_encode($orders->first()->items) }}
// blade output
[{"SKU":"CM10361","qty":1},{"SKU":"CM10361","qty":1},{"SKU":"CM10361","qty":1},{"SKU":"CM10361","qty":1},{"SKU":"CM10361","qty":1}]
如何访问'SKU'和'qty'键?喜欢$items->SKU
?
由于
答案 0 :(得分:0)
在您的视图中,您有一个集合,尝试通过方法each
迭代项目,如下所示:
$orders->each(function ($item, $key) {
//here your stuff
});
答案 1 :(得分:0)
// controller
$orders = Order::with('orderAuthor')->orderBy('id', 'desc')->get();
//loop through results
foreach ($orders as $order)
{
//now decode the json
$decoded_order = json_decode($order);
echo $sku = $decoded_order->SKU;
}
答案 2 :(得分:0)
我不明白为什么你是json_encoding
视图上的items
对象(即你将它转换为字符串),当你真的想要作为一个数组访问它时。我猜测items
列是可变的(Laravel自动编码/解码),所以如果这是正确的,我认为你应该这样做:
@foreach ($orders->first()->items as $item)
{{ $item['SKU'] }}
@endforeach
答案 3 :(得分:0)
这是正确的解决方案,最后
@foreach ($orders as $order)
@foreach ($order->items as $item)
{{ $item['qty'] }}
@endforeach
@endforeach
答案 4 :(得分:0)
//loop through results
@foreach ($orders as $orderKey=>$orderValue)
$sku = $orderValue->SKU;
$qty = $orderValue->qty;
<tr>
<td>{{$sku}}</td>
<td>{{$qty}}</td>
</tr>
@endforeach