20

I have a JSON array

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

How would I search for 8097 and get the content?

3
  • can create a loop to go through peope->id array Commented Aug 8, 2011 at 19:41
  • 1
    How many people are represented? If it is sufficiently small, then one of the search loops presented below could work well. If it is very large, you might need something else. Commented Aug 8, 2011 at 19:46
  • Also, are the entries always in increasing order of id? If so, an algorithm built around that could produce something much more efficient than looping through every entry. Commented Aug 8, 2011 at 19:48

3 Answers 3

43

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I totally forgot to do the ->people part every time. works perfectly.
23

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

2 Comments

I think you have the arguments for array_map out of order.
I used array_map instead of array_filter. Fixed now.
5

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

1 Comment

PHP doesn't have a binary search already in it? Interesting. I don't think I've had to code a binary search in a decade. Oh - I just noticed, this answer IS a decade old. LOL! Google, big fail. There is an array_search function: echo array_search("red",$a); Although in the OP's JSON, there's the useless column "people" (it's for formatting, not content, assuming this is all the JSON they have), which creates a complication.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.