如何在PHP中搜索嵌套的JSON数组

时间:2019-03-07 21:29:14

标签: php arrays json

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

我的问题与StackOverflow(How to search through a JSON Array in PHP)上的已回答问题相似,但是我希望能够在任一中找到一个ID为 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;
    }
}

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

在这种情况下,只需执行两个循环即可。

$json = json_decode('{
    "people": [
        {
            "id": "8080",
            "content": "foo"
        },
        {
            "id": "8097",
            "content": "bar"
        }
    ],
    "dogs": [
        {
            "id": "8081",
            "content": "spot"
        },
        {
            "id": "8091",
            "content": "max"
        }
    ]
}');

foreach($json as $key=>$value){
    //$key = people or dogs
    //$value = stdClass()

    foreach($value as $item)
    {
        if($item->id == "8097")
        {
            echo $item->content;
        }
    }    
}

输出

bar

Sandbox

如果我们使用8081而不是8097,我希望得到“ spot”。经过测试,我确实得到了(在狗身上)。