如何过滤数组以获取laravel中两个不同对象中的特定列
Posted
技术标签:
【中文标题】如何过滤数组以获取laravel中两个不同对象中的特定列【英文标题】:how to filter an array to get specific columns in two different objects in laravel 【发布时间】:2021-10-29 23:37:28 【问题描述】:我需要这样的回应。
"result": [
"properties":
"device_id": 15196,
"device_name": Street Light 1,
"state" : 1,
"status": 1,
,
"geometry":
"lat":33.7017,
"lng": 73.0228
,
"properties":
"device_id": 15196,
"device_name": Street Light 1,
"state" : 1,
"status": 1,
,
"geometry":
"lat":33.7017,
"lng": 73.0228
,
]
我的代码在下面。我只想从我的整个回复中分出两个字段“lat”和“lng”。我的 sql 查询是正确的,但我想创建上面提到的自定义响应
$get1 = DB::table('device_user')
->join('devices', 'devices.id', '=', 'device_user.device_id')
->join('components', 'devices.id', '=', 'components.device_id')
->select('devices.id as device_id', 'devices.name', 'devices.status', 'components.state', 'components.type', 'devices.lat', 'devices.lng')
->where('device_user.user_id', $request->user_id)
->where('components.type', $type)
->get();
$array = [];
foreach ($get1 as $key => $value)
array_push($array, ["properties" => $value, "geometry" => $value->lat]);
return $array;
【问题讨论】:
【参考方案1】:我试了很多次,终于搞定了。
$get = DB::table('device_user')
->join('devices', 'devices.id', '=', 'device_user.device_id')
->join('components', 'devices.id', '=', 'components.device_id')
->select('devices.id as device_id', 'devices.name', 'devices.status', 'components.state', 'components.type', 'devices.lat', 'devices.lng')
->where('device_user.user_id', $request->user_id)
->where('components.type', $type)
->get();
$finalarray =[];
foreach ($get as $key => $value)
array_push($finalarray, ["properties" => ['device_id' => $value->device_id, 'name' => $value->name, 'status' => $value->status, 'state' => $value->state, 'type' => $value->type, ], "geometry" => ["coordinates" => ['lat' => $value->lat, 'lng' => $value->lng]]]);
【讨论】:
【参考方案2】:试试这个
$get1 = DB::table('device_user')
->join('devices', 'devices.id', '=', 'device_user.device_id')
->join('components', 'devices.id', '=', 'components.device_id')
->select('devices.id as device_id', 'devices.name', 'devices.status', 'components.state', 'components.type', 'devices.lat', 'devices.lng')
->where('device_user.user_id', $request->user_id)
->where('components.type', $type)
->get();
$main_array = [];
foreach ($get1 as $key => $value)
$main_array[$key]['properties'] = array('device_id' => $value->device_id, 'device_name' => $value->device_name, 'state' => $value->state, 'status' => $value->status);
$main_array[$key]['geometry'] = array('lat' => $value->lat, 'lng' => $value->lng);
return $main_array;
【讨论】:
以上是关于如何过滤数组以获取laravel中两个不同对象中的特定列的主要内容,如果未能解决你的问题,请参考以下文章
如何以交替顺序对两个不同对象列表的 XML 数组项进行排序?