You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何过滤数组拆分字段到两个对象生成指定响应格式

代码修改实现方案

核心修改逻辑

  • 遍历查询结果时,分别构造properties和geometry两个结构体
  • properties字段仅保留业务属性,将原查询的name字段映射为目标要求的device_name键
  • geometry字段单独封装lat和lng两个坐标属性
  • 最终返回结果外层包裹result键,匹配要求的响应格式

完整修改后代码

$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) {
    // 构造properties结构体,过滤不需要的字段、映射字段名
    $properties = [
        'device_id' => $value->device_id,
        'device_name' => $value->name,
        'state' => $value->state,
        'status' => $value->status
    ];
    // 构造geometry坐标结构体
    $geometry = [
        'lat' => $value->lat,
        'lng' => $value->lng
    ];
    array_push($array, [
        'properties' => $properties,
        'geometry' => $geometry
    ]);
}
// 外层包裹result键返回
return ['result' => $array];

可选优化写法(Laravel集合操作)

如果习惯用Laravel集合的链式操作,可以替换遍历逻辑,写法更简洁:

$result = $get1->map(function ($value) {
    return [
        'properties' => [
            'device_id' => $value->device_id,
            'device_name' => $value->name,
            'state' => $value->state,
            'status' => $value->status
        ],
        'geometry' => [
            'lat' => $value->lat,
            'lng' => $value->lng
        ]
    ];
})->toArray();
return ['result' => $result];

内容的提问来源于stack exchange,提问作者Atif Mahmood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 20:36:02