php - 从 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
。我该怎么做?
解决方案
由于您没有使用 的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);
}
推荐阅读
- bash - 如何使whiptail中的输入框超时?
- ios - 用作子 VC 时,来自 VNDetectRectangleRequest 的边界框大小不正确
- directory - wsl:无法移动“/home”
- python - 获取“IndexError:无法从空序列中选择”并且不知道为什么我的序列为空
- bash - 如何在 bash 中迭代 grep 上下文组
- python - 如何使用 selenium-python 检查元素是否具有属性
- c# - WPF - 单击 ListView 后设置焦点
- raspbian - 树莓派上的 kismet 失败 ./configure libwebsockets
- r - 在 HTML 中呈现分组列表
- pyspark - 将数据流式传输到增量表并保存最新值