使用索引转换JSON数据并发送

时间:2017-04-12 13:03:12

标签: php json laravel api laravel-5.4

我想转换我收到的json数据并将其发送到请求的应用程序,以便他们可以轻松获取关键值

//this is what i'm getting in postman

{
    "dropdown_data": {
        "driving_regions": [{
            "name": "East India"
        }, {
            "name": "West India"
        }],
        "employment_types": [{
            "type": "Owner"
        }, {
            "type": "Other"
        }],
        "event_names": [{
            "name": "Transport Mitra"
        }, {
            "name": "Other"
        }],
        "languages": [{
            "name": "English"
        }, {
            "name": "Spanish"
        }, {
            "name": "Hindi"
        }]
    },
    "user_details": {

     }
}

//i want to transform like the below

{
    "0": "dropdown_data",
    "dropdown_data": {
        "0": "driving_regions",
        "driving_regions": [{
            "name": "East India"
        }, {
            "name": "West India"
        }],
        "1": "employment_types",
        "employment_types": [{
            "type": "Owner"
        }, {
            "type": "Other"
        }],
        "2": "event_names",
        "event_names": [{
            "name": "Transport Mitra"
        }, {
            "name": "Other"
        }],
        "3": "languages",
        "languages": [{
            "name": "English"
        }, {
            "name": "Spanish"
        }, {
            "name": "Hindi"
        }]
    },
    "1": "user_details",
    "user_details": {

    }
}

在我的控制器中我只是获取数据并输入变量,然后我将以json的形式返回,如下所示

   return Response::json([
        'dropdown_data' => [
            'castes' => $castes->all(),
            'driving_regions' => $driving_regions->all(),
            'employment_types' => $employment_types->all(),
            'event_names' => $event_types->all(),
            'languages' => $languages->all()
        ],
            'user_details' => $user_details,
    ]);

谢谢

1 个答案:

答案 0 :(得分:0)

将它们投射到对象:

return Response::json([
    'dropdown_data' => [
        'castes' => (object) $castes->all(),
        'driving_regions' => (object) $driving_regions->all(),
        'employment_types' => (object) $employment_types->all(),
        'event_names' => (object) $event_types->all(),
        'languages' => (object) $languages->all()
    ],
        'user_details' => $user_details,
]);