【问题标题】:Reading the Guzzle response with some nested JSON objects使用一些嵌套的 JSON 对象读取 Guzzle 响应
【发布时间】:2017-07-31 23:00:38
【问题描述】:

我使用 Guzzle 库向我的 api 发出 http 请求,如下所示:

$client = new Client();
            $response = $client->request(
                'GET',
                config('some_url');
            $serverResponse = json_decode($response->getBody(),true);
            if ($serverResponse['result']) {
                $data = $serverResponse['data'];

现在我得到了响应

{
    "result": true,
    "data": {
        "101": {
            "id": 101,
            "name": "ABCD",
            "age" : 24
            },
         "102": {
            "id": 102,
            "name": "EFGH",
            "age" : 24
            },
         "103": {
            "id": 103,
            "name": "IJKL",
            "age" : 24
            },
}
}

问题是我需要读取对象模型 101,102,103 并将其推送到单独的数组中。为此,我尝试将对象作为以下选项。但我无法得到结果而不是错误。

$obj = $data[0];

它返回未定义的偏移量:0 错误

【问题讨论】:

  • 狂吃不醉

标签: php json guzzle


【解决方案1】:

因为您的数据是手动索引的,而不是像这样的:

{
    "data": {
        0: {
           "id": 101,
           ...
        },
        1: {
           "id": 102,
           ...
        },
        ...
     }
}

您需要在获取数据时指定这些索引。例如:

$data["101"]

要对动态设置的数据执行此操作,您可以使用array_keys

$obj = $data[array_keys($data)[0]];

使用array_keys 允许您通过$data 的数字索引搜索$data

【讨论】:

  • 它是动态的。所以我不能叫那个。只有这种方式才能从索引中调用。有可能吗?
【解决方案2】:

如果您只是想重新索引数组以便键为[0][1][2] 等,您可以使用以下命令:

$newArray = array_values($data);

然后您将能够使用$newArray[0] 访问第一个子数组,使用$newArray[1] 访问第二个子数组,等等。

【讨论】:

    【解决方案3】:

    您可以将响应转换为对象,然后您可以访问以下属性。

    $obj = json_decode($response->getBody());
    $one_zero_one = $obj->data->{101};
    

    【讨论】:

      猜你喜欢
      • 2020-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-08
      • 2020-11-09
      • 2022-11-21
      相关资源
      最近更新 更多