【问题标题】:Get key names from JSON array从 JSON 数组中获取键名
【发布时间】:2019-08-07 23:31:34
【问题描述】:

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

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

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

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

但我找不到重置的方法,在本例中为 424。我该怎么做?

【问题讨论】:

  • 您的$response 分配不是有效的PHP 语法。
  • 你的意思是写$response = json_decode('{...}');
  • 使用array_keys() 而不是key();
  • 修正了语法

标签: php json key


【解决方案1】:

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

那么你可以使用array_keys()来获取cpu数组的所有key。

$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);
}

【讨论】:

    【解决方案2】:

    您也只需要遍历cpu 值;可以直接在foreach中提取密钥:

    $results = $response->result;
    foreach ($results as $item) {
        foreach ($item->cpu as $key => $cpu) {
            echo "$key\n";
        }
    }
    

    输出:

    423
    424
    

    Demo on 3v4l.org

    【讨论】:

      猜你喜欢
      • 2016-06-22
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 2017-12-09
      相关资源
      最近更新 更多