Json array to json php



我有以下json。 retailer_info 属性是 1 个元素的数组。

{
"data": {
"user": {
"id": 18626,
"first_name": "Sip",
"last_name": "Gemmayzeh",
"retailer_info": [
{
"id": 231,
"retailer_id": 18626,
"store_id": 344,
"created_at": "2018-02-26 09:32:58",
"updated_at": "2018-02-26 09:32:58"
}
],
"op_city": {
"id": 1,
"ref": "Beirut",
"currency_id": 5,
"currency": {
"id": 5,
"symbol": "USD"
}
},
"team_lead": null,
"op_city_languages": [
{
"id": 1,
"locale": "en",
"name": "English"
}
]
}
},
"errors": false
}

我想将数组转换为单个 json 对象,如下所示

"retailer_info": {
"id": 231,
"retailer_id": 18626,
"store_id": 344,
"created_at": "2018-02-26 09:32:58",
"updated_at": "2018-02-26 09:32:58"
},

我的 laravel 代码只是像这样获取模型

$user = User::with('retailerInfo', 'opCity', ...)->get();

我尝试了以下方法,但没有奏效。 它使数组保持原样。

$user->retailerInfo = $user->retailerInfo[0];
$user->retailerInfo = reset($user->retailerInfo);

这应该可以为您解决问题。我遇到了类似的问题,我想"取消嵌套"一个数组,这有助于我解决它。

听起来很奇怪,因为->get()总是返回一个集合 应使用->first()->firstOrFail()仅检索一个元素。 或者,可以调用->each($callback)对每个元素应用回调。 在 with(( 中使用 [] 括号

$user = User::with(['retailerInfo', 'opCity', ...])->firstOrFail();
dd($user->retailerInfo->first());

User::with(['retailerInfo', 'opCity', ...])->each(function($user) {
dump($user->retailerInfo->first());
});

最新更新