9阅网

您现在的位置是:首页 > 知识 > 正文

知识

php - Laravel从JSON对象中多维度访问数据.

admin2022-11-07知识18

我正在写一个Laravel的API, 它可以消耗一个已经存在的API, 我需要自己的 "中间人 "API, 因为它在发送请求之前插入敏感数据, 因为我不想在客户端存储这些敏感数据. 我需要一个自己的 "中间人 "API, 因为它在发送请求之前会插入敏感数据, 因为我不想在客户端存储这些敏感数据.

我可以正常获取数据,但我希望能够使用路由参数来访问返回的JSON对象的各种 "维度"。

目前,如果我导航到 /get/status 我得到的回复是这样的。

{
    "fuelAmount": 8,
    "fuelAmountLevel": 11,

    "tyrePressure": {
        "frontLeftTyrePressure": "Normal",
        "frontRightTyrePressure": "Normal",
        "rearLeftTyrePressure": "Normal",
        "rearRightTyrePressure": "Normal",
        "timestamp": "2020-05-19T20:10:49+0000"
    },

    "heater": {
        "seatSelection": {
            "frontDriverSide": false,
            "frontPassengerSide": false,
            "rearDriverSide": false,
            "rearPassengerSide": false,
            "rearMid": false
        },
        "status": "off",
        "timer1": {
            "time": "17:30",
            "state": false
        },
        "timer2": {
            "time": "00:00",
            "state": false
        },
        "timestamp": "2020-05-19T11:28:19+0000"
    },
}

我希望能够做的是导航到 get/status/fuelAmount 并且只得到燃料金额。所以我只会得到 8 作为回应。目前我可以做到这一点,但我不知道如何有效地在多个层次上做到这一点。因为获取燃料数量只是一个 "更深的层次",我也希望能够做到以下几点 /get/status/heater/timer1/time 而只得到 17:30 作为响应。

目前的代码是这样的

public function vehicleGet($vMethod, $dataKey= null) {
    $response = Http::withHeaders([
        // bunch of headers needed to successfully request data
    ])
    ->withBasicAuth("user", config('app.mySecret'))
    ->get($this->url);

    if(isset($dataKey)) {
        return $response[$dataKey];
    }else {
        return $response->json();;
    }
}

Laravel的路线

Route::get("get/{vMethod}/{dataKey?}", "[email protected]")->where('dataKey', '.*');

所以就像我说的,如果我去 /get/status/heater 我成功申请了 status 端点,而我只能打印出第三方API的 heater 数据。

{
    "seatSelection": {
        "frontDriverSide": false,
        "frontPassengerSide": false,
        "rearDriverSide": false,
        "rearPassengerSide": false,
        "rearMid": false
    },
    "status": "off",
    "timer1": {
    "    time": "17:30",
    "    state": false
    },
    "timer2": {
        "time": "00:00",
        "state": false
    },
    "timestamp": "2020-05-19T11:28:19+0000"
}

但如果我去 /get/status/heater/timer1/ 我得到 Undefined index: heater/timer1 因为很明显这个键在初始JSON对象中并不存在。

所以我必须以某种方式在这个返回语句中添加更多的键 return $response[$dataKey] 视乎 dataKey URL中的参数。我可以对该字符串进行爆炸,得到一个包含每个键的数组,但我仍然需要以某种方式将每个键添加到返回语句中。

我可以在路由中添加更多的参数, 而不是使用一个通配符参数, 但是我需要为每一个可选的参数写一堆if语句, 检查它是否被设置, 如果是, 在显示JSON数据时使用它作为一个键?



【回答】:

替换你当前的 isset 代码块的内容如下:

if(isset($dataKey)) 
{
    $dt = $response;
    $searchFound = 1;
    $dataKey = explode("/" , $dataKey);
    foreach($dataKey as $key => $val)
    {
        if(isset($dt[$val])) 
        {
          $dt = $dt[$val];
        } else 
        {
          $searchFound = 0;
          break;
        }
    }

    return $dt;

}else {
    return $response->json();;
}