如何在 PHP 中搜索 JSON 数组

2022-08-30 20:16:33

我有一个 JSON 数组

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

如何搜索 8097 并获取内容?


答案 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;
    }
}

答案 2

json_decode() 它,并像对待任何其他数组或 StdClass 对象一样处理

$arr = json_decode('{
  "people":[
    {
      "id": "8080",
      "content": "foo"
    },
    { 
      "id": "8097",
      "content": "bar"
    }
  ]
}',true);

$results = array_filter($arr['people'], function($people) {
  return $people['id'] == 8097;
});


var_dump($results);

/* 
array(1) {
  [1]=>
  array(2) {
    ["id"]=>
    string(4) "8097"
    ["content"]=>
    string(3) "bar"
  }
}
*/