如何在PHP中搜索JSON数组
我有一个JSON数组如何在PHP中搜索JSON数组,php,arrays,json,Php,Arrays,Json,我有一个JSON数组 { "people":[ { "id": "8080", "content": "foo" }, { "id": "8097", "content": "bar" } ] } 我如何搜索8097并获取内容?将其视为任何其他数组或StdClass对象 $arr = json_decode('{ "people":[ { "id": "8080", "
{
"people":[
{
"id": "8080",
"content": "foo"
},
{
"id": "8097",
"content": "bar"
}
]
}
我如何搜索8097并获取内容?将其视为任何其他数组或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"
}
}
*/
使用函数将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;
}
}
如果您有相当少的“人”对象,那么前面的答案将适用于您。考虑到您的示例的ID在8000范围内,我怀疑查看每个ID可能并不理想。因此,这里有另一种方法,可以在找到正确的人之前对更少的人进行检查(只要这些人按ID排序):
//以JSON作为字符串存储在$jsonStr变量中开始
//从JSON中提取排序数组
$sortedArray=json_decode($jsonStr,true);
$target=8097//可以将其更改为需要查找的任何其他ID
$targetPerson=findContentByIndex($sortedArray,$target,0,count($sortedArray));
if($targetPerson==-1)//未找到匹配项
回显“未找到匹配项”;
函数findContentByIndex($sortedArray、$target、$low、$high){
//这基本上是一个二进制搜索
if($high$target)
//搜索剩余对象的前一半
返回findContentByIndex($sortedArray、$target、$low、$mid-1);
否则如果($sortedArray[$mid]['id']<$target)
//搜索剩余对象的后半部分
返回findContentByIndex($sortedArray,$target,$mid+1,$high);
其他的
//找到匹配项!退回!
返回$sortedArray[$mid];
}
可以创建一个循环来遍历peope->id array代表了多少人?如果它足够小,那么下面介绍的其中一个搜索循环可以很好地工作。如果它非常大,您可能需要其他东西。此外,条目是否总是按id的递增顺序排列?如果是这样的话,一个围绕它构建的算法可能会产生比循环遍历每个条目更有效的结果。我认为你有无序的理由。我使用了数组映射而不是数组过滤器。现在修好了。我每次都忘了做->人物部分。PHP中没有二进制搜索吗?有趣。我不认为十年来我必须编写二进制搜索代码。哦,我刚刚注意到,这个答案已经有十年历史了。英雄联盟谷歌,大失败。有一个数组搜索功能:回声数组搜索(“红色”,$a);尽管在OP的JSON中,有一个无用的列“people”(它用于格式化,而不是内容,假设这就是他们所有的JSON),这会造成复杂的问题。
//start with JSON stored as a string in $jsonStr variable
// pull sorted array from JSON
$sortedArray = json_decode($jsonStr, true);
$target = 8097; //this can be changed to any other ID you need to find
$targetPerson = findContentByIndex($sortedArray, $target, 0, count($sortedArray));
if ($targetPerson == -1) //no match was found
echo "No Match Found";
function findContentByIndex($sortedArray, $target, $low, $high) {
//this is basically a binary search
if ($high < low) return -1; //match not found
$mid = $low + (($high-$low) / 2)
if ($sortedArray[$mid]['id'] > $target)
//search the first half of the remaining objects
return findContentByIndex($sortedArray, $target, $low, $mid - 1);
else if ($sortedArray[$mid]['id'] < $target)
//search the second half of the remaining objects
return findContentByIndex($sortedArray, $target, $mid + 1, $high);
else
//match found! return it!
return $sortedArray[$mid];
}