如何在 PHP 中搜索 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6987611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:45:00  来源:igfitidea点击:

How to search through a JSON Array in PHP

phparraysjson

提问by consindo

I have a JSON array

我有一个 JSON 数组

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

How would I search for 8097 and get the content?

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

回答by Tim Cooper

Use the json_decodefunction to convert the JSON string to an array of object, then iterate through the array until the desired object is found:

使用该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;
    }
}

回答by Mchl

json_decode()it and treat like any other array or StdClass object

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"
  }
}
*/

回答by Jeffrey Blake

If you have a fairly small number of "people" objects, then the previous answers will work for you. Given that your example has IDs in the 8000 range, I suspect looking at every single ID might not be ideal. So here is another method that will examine far fewer people before finding the right one (as long as the people are in order of ID):

如果您的“人”对象数量很少,那么前面的答案对您有用。鉴于您的示例具有 8000 范围内的 ID,我怀疑查看每个 ID 可能并不理想。因此,这是另一种方法,可以在找到合适的人之前检查少得多的人(只要人是按 ID 排序的):

//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];
}