如何在PHP中搜索JSON数组

时间:2011-08-08 19:39:40

标签: php arrays json

我有一个JSON数组

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

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

3 个答案:

答案 0 :(得分:24)

json_decode功能可以帮助您:

$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;
    }
}

答案 1 :(得分:17)

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

答案 2 :(得分:4)

如果您拥有相当少量的“人物”对象,那么之前的答案将适合您。鉴于您的示例具有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];
}