一尘不染

如何在PHP中搜索JSON数组

json

我有一个JSON数组

{
  "people":[
    {
      "id": "8080",
      "content": "foo"
    },
    { 
      "id": "8097",
      "content": "bar"
    }
  ]
}

我将如何搜索8097并获取内容?


阅读 460

收藏
2020-07-27

共1个答案

一尘不染

使用该json_decode函数将JSON字符串转换为对象数组,然后遍历该数组直到找到所需的对象:

$str = '{
  "people":[
    {
      "id": "8080",
      "content": "foo"
    },
    { 
      "id": "8097",
      "content": "bar"
    }
  ]
}';

$json = json_decode($str);
foreach ($json->people as $item) {
    if ($item->id == "8097") {
        echo $item->content;
    }
}
2020-07-27