【问题标题】:How to search through nested JSON arrays in PHP如何在 PHP 中搜索嵌套的 JSON 数组
【发布时间】:2019-03-07 21:29:14
【问题描述】:

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

我的问题类似于 StackOverflow (How to search through a JSON Array in PHP) 上已回答的问题,但我希望能够在 people 中找到 item by id strong>dog任何其他嵌套数组。本质上,我想将 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;
    }
}

非常感谢任何帮助。

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      $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”。并进行测试,我确实得到了(在狗身上)。

      【讨论】:

      • 谢谢!!!你不仅帮我解决了我的问题,还教我在 foreach 中正确使用 as $key=>$value。我一直认为你必须要一个特定的项目。如果我是正确的,如果我知道它的名称,此方法将允许我从数组中提取任何“键/值”对。再次感谢!
      • 如果 id 属性是唯一的,那么我们应该看到使用了 break
      猜你喜欢
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 2011-10-22
      • 2021-08-14
      • 2023-02-08
      • 1970-01-01
      相关资源
      最近更新 更多