Как выполнить поиск по массиву JSON в PHP


У меня есть массив JSON

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

Как бы я искал 8097 и получал контент?

Author: Jeffrey Blake, 2011-08-08

3 answers

В 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;
    }
}
 22
Author: Tim Cooper, 2011-08-08 19:42:58

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"
  }
}
*/
 16
Author: Mchl, 2014-10-18 02:23:43

Если у вас довольно небольшое количество объектов "люди", то предыдущие ответы будут работать для вас. Учитывая, что в вашем примере идентификаторы находятся в диапазоне 8000, я подозреваю, что просмотр каждого отдельного идентификатора может быть не идеальным. Итак, вот еще один метод, который проверит гораздо меньше людей, прежде чем найти нужного (при условии, что люди находятся в порядке идентификации):

//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];
}
 4
Author: Jeffrey Blake, 2011-08-08 20:16:30