php - 如何在 PHP 中搜索嵌套的 JSON 数组
问题描述
如果我没有使用正确的术语,我很抱歉,我还在学习。我试图弄清楚如何在其中包含嵌套数组的 JSON 数组中搜索特定值,然后返回关联值。
我的问题类似于 StackOverflow 上已回答的问题(How to search through a JSON Array in PHP),但我希望能够在people或dog或任何其他嵌套数组中通过 id 找到项目。本质上,我想将foreach 中的下面转换为通配符。people
这是我的 JSON 数据 - http://foothillertech.com/student/webdesign/2018/2018benrud2/tinker/dataIntro2/test/data.json
foreach($json->people as $item)
{
if($item->id == "8097")
{
echo $item->content;
}
}
任何帮助是极大的赞赏。
解决方案
如果 id 在数据中是唯一的,则可以合并内部数组并按 id 对其进行索引。
$data = json_decode($json, true);
$merged = array_merge(...array_values($data));
$indexed = array_column($merged, null, 'id');
然后您可以通过 id 查找任何项目。
echo $indexed['8097']['content'] ?? 'not found';
这仅在 id 是唯一的情况下才有效。如果没有,按 id 索引会导致数据丢失。
推荐阅读
- python - Python 和雪花无法将转换为 JSON 的数据帧插入到雪花上的变体字段中
- prolog - Prolog - 无法按预期运行程序
- laravel - 404 Not Found nginx /1.18.0 aws laravel 项目
- python - 如何使用 CSS 和 Bootstrap 扩展文本宽度
- android - 填充并发出 StateFlow 列表
- java - 找到矩阵的行列式
- javascript - 按数组中的多个属性分组
- python - 如何从列表中的元组中的元素创建字符串
- css - 隐藏父级,但使用 CSS 显示子级 div
- r - 加快 R 循环中的 Rcpp 评估