[英]How to remove a key from an object not array in laravel
I get data from database using this query我使用此查询从数据库中获取数据
$cats = Category::with(['cat_trans' => function($q) use($lang){
$q->where('lang_code', $lang);
}])->with(['cat_prod' => function($query) use ($lang,$currency){
$query->with(['pro_trans' => function ($q) use ($lang){
$q->where('lang_code', $lang);
}]);
////////////
$query->with(['pro_price' => function ($q) use ($currency){
$q->with('currency_code')->where('cur_code', $currency);
}]);
///////////
}])->whereHas('account_type', function($qr) use ($account_type){
$qr->where('account_type_id', $account_type);
})->get();
I'm trying to remove the empty objects from the result, when I tried this I got the following response我试图从结果中删除空对象,当我尝试这个时,我得到了以下响应
{
"1": {
"id": 1,
"parent_id": null,
"order": 1,
"name": "Moblie",
"slug": "mobile-1",
"created_at": "2018-07-08 09:41:08",
"updated_at": "2018-07-08 10:30:17",
"cat_trans": [
{
"id": 1,
"category_id": 1,
"field": "title",
"value": "Mobile",
"lang_code": "en",
"created_at": "2018-07-08 09:51:59",
"updated_at": "2018-07-08 09:51:59"
},
{
"id": 2,
"category_id": 1,
"field": "desc",
"value": "smart",
"lang_code": "en",
"created_at": "2018-07-08 09:52:41",
"updated_at": "2018-07-08 09:52:41"
},
{
"id": 12,
"category_id": 1,
"field": "slug",
"value": "mobile-1",
"lang_code": "en",
"created_at": null,
"updated_at": null
}
],
}
}
I want to remove the key "1" from all the responses.我想从所有响应中删除键“1”。
I used unset to get this value using this code我使用 unset 使用此代码获取此值
foreach ($cats as $k) {
if (count($k->cat_prod) == 0) {
unset($cats[$va]);
}
$va++;
}
Then I tried using array_values but it displays that I can just use array_values on an array not an object.然后我尝试使用array_values,但它显示我只能在数组上使用array_values,而不是object。
You can remove key "1" by simply doing 您只需执行以下操作即可删除键“ 1”
array_values((array)$cats)
You were receiving error for this function like "Can Only be used on array" was due to Laravel Query returns object , so you just need to do type conversion on it. 由于Laravel Query返回对象,您会收到此函数错误,例如“只能在数组上使用”,因此您只需要对其进行类型转换。
$ cats-> toArray()如果您需要将对象转换为数组或在某些特定条件下进行转换
您的输出看起来像JSON,因此您可以执行以下操作以消除1
:
json_encode( $cats->{1} );
You can use laravel simple method mapWithKeys()您可以使用 laravel 简单方法 mapWithKeys()
$cats = $cats->mapWithKeys(function ($item) {
return $item > 2;
});
$keyed->all(); $keyed->all();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.