How to search through a JSON Array in PHP
I have a JSON array
{
"people":[
{
"id": "8080",
"content": "foo"
},
{
"id": "8097",
"content": "bar"
}
]
}
How would I search for 8097 and get the content?
Solution 1:
Use the json_decode
function to convert the JSON string to an array of object, then iterate through the array until the desired object is found:
$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;
}
}
Solution 2:
json_decode()
it and treat like any other array or StdClass object
$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"
}
}
*/
Solution 3:
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):
//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];
}