首页 > 解决方案 > 从 JSON 数组中获取键名

问题描述

我需要从这种 JSON 响应中提取所有 cpu id:

$response = json_decode('{
  "code": 26,
  "result": {
    "0": {
      "cpu": {
        "423": {
          "prod": "Intel",
          "model": "i5-8300H",
        },
        "424": {
          "prod": "Intel",
          "model": "i7-8750H",
        }
      }
    }
  }
}');

我设法423使用以下代码获得了第一个 ID:

$response = $response->result;
foreach ($response as $item) {
            $key = key((array)$item->cpu);
        }

但在这种情况下,我找不到重置的方法424。我该怎么做?

标签: phpjsonkey

解决方案


由于您没有使用 的true第二个参数json_decode(),因此所有元素都被解析为对象,而不是数组。用于json_decode(..., true)获取数组。

然后你可以使用array_keys()来获取cpu数组的所有键。

$response = json_decode('
{
  "code": 26,
  "result": {
    "0": {
      "cpu": {
        "423": {
          "prod": "Intel",
          "model": "i5-8300H"
        },
        "424": {
          "prod": "Intel",
          "model": "i7-8750H"
        }
      }
    }
  }
}', true);
$response = $response['result'];
foreach ($response as $item) {
    $keys = array_keys($item['cpu']);
    var_dump($keys);
}

推荐阅读