我应该如何解码正确的json响应?

时间:2019-06-27 04:49:24

标签: php json laravel

我正在使用Laravel 5.7来构建提供JSON响应的API。我正在创建以下JSON,但需要进行一些更改。该表包含booking_pics列,其中使用分开存储了多个图像。我想在json中获取数组中的对象。我显示的是json,但只有最后一张图像显示了,其他没有,需要解决。

控制器:

{
    "success": "1",
    "data": [
        {
            "id": 1,
            "booking_list_id": 1,
            "booking_id": 1,
            "booking_name": "hockey stadium",
            "booking_area": "kolhapur",
            "booking_status": 0,
            "time": "6.00 am to 8.00pm",
            "booking_pics": [
                {
                    "image": "http://192.168.1.132:8000/images/ground_pic/2.jpg"
                }
            ],
            "available_sports": "hockey,cricket",
            "booking_amenities": "parking,toilet,water",
            "booking_rating": 4.5,
            "booking_area_address": "MSEB Ring Road, Datta Colony, Kolhapur, Maharashtra, 416008",
            "longitude": "85.501980",
            "latitude": "23.624420",
            "updated_at": "2019-06-26 16:42:02",
            "created_at": "0000-00-00 00:00:00"
        }
    ]
}

json响应:

{
    "success": "1",
    "data": [{
        "id": 1,
        "booking_list_id": 1,
        "booking_id": 1,
        "booking_name": "hockey stadium",
        "booking_area": "kolhapur",
        "booking_status": 0,
        "time": "6.00 am to 8.00pm",
        "booking_pics": [{
                "image": "http://192.168.1.132:8000/images/ground_pic/1.jpg"
            },
            {
                "image": "http://192.168.1.132:8000/images/ground_pic/2.jpg"
            }
        ],
        "available_sports": "hockey,cricket",
        "booking_amenities": "parking,toilet,water",
        "booking_rating": 4.5,
        "booking_area_address": "MSEB Ring Road, Datta Colony, Kolhapur, Maharashtra, 416008",
        "longitude": "85.501980",
        "latitude": "23.624420",
        "updated_at": "2019-06-26 16:42:02",
        "created_at": "0000-00-00 00:00:00"
    }]
}

必需的json:

import style from './index.css'

2 个答案:

答案 0 :(得分:0)

  

这样做吧

        foreach($get_booking_details as $item)
        {
            foreach(explode(",",$item->booking_pics) as $items)
            {
               $item->booking_pics["image"][] = $items;
            }
        }

答案 1 :(得分:0)

最快的方法是创建模型并将数据库中的数据转换为json

在模型中

protected $casts = [
    'booking_pics' => 'json',
];