首页 > 解决方案 > 如何在 PHP 中搜索嵌套的 JSON 数组

问题描述

如果我没有使用正确的术语,我很抱歉,我还在学习。我试图弄清楚如何在其中包含嵌套数组的 JSON 数组中搜索特定值,然后返回关联值。

我的问题类似于 StackOverflow 上已回答的问题(How to search through a JSON Array in PHP),但我希望能够在peopledog任何其他嵌套数组中通过 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;
    }
}

任何帮助是极大的赞赏。

标签: phparraysjson

解决方案


如果 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 索引会导致数据丢失。


推荐阅读