简体   繁体   中英

Laravel working with JSON in MySQL

Hi I can't display JSON data from MySQL correctly, I need to access 'SKU' and 'qty' keys for each item in JSON individually. My code looks like this:

 // 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}] 

How can I access 'SKU' and 'qty' keys? Like $items->SKU ?

Thanks

At your view your have a collection, try to iterate the items through the method each , something like this:

$orders->each(function ($item, $key) {
  //here your stuff
});
// 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;

}

I don't understand why you are json_encoding the items object on your view (ie you're converting it to a string), when you actually want to access it as an array. I'm guessing that the items column is mutable (Laravel encodes/decodes it automatically), so if that's correct, I think you should just do:

@foreach ($orders->first()->items as $item)
    {{ $item['SKU'] }}
@endforeach

This was the correct solution, finally

@foreach ($orders as $order)
    @foreach ($order->items as $item)
         {{ $item['qty'] }}
    @endforeach
@endforeach
//loop through results
@foreach ($orders as $orderKey=>$orderValue)
        $sku = $orderValue->SKU;
        $qty = $orderValue->qty;
        <tr>
                <td>{{$sku}}</td>
                <td>{{$qty}}</td>
        </tr>
@endforeach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM