Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search through a JSON Array in PHP

Tags:

I have a JSON array

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

How would I search for 8097 and get the content?

like image 303
consindo Avatar asked Aug 08 '11 19:08

consindo


1 Answers

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;
    }
}
like image 96
Tim Cooper Avatar answered Sep 21 '22 17:09

Tim Cooper