Tony Tony - 9 months ago 53
JSON Question

Php json decoding with multiple objects


"articles": [
"id": 1,
"name": "Josh"
"id": 2,
"name": "Jenny"
"id": 3,
"name": "Chris"

How do i search names by id?

What should I do if i want select only Josh?

Now I'm decoding json with php and foreach loop.

$url = "articles.json";
$json = json_decode(file_get_contents($url));
foreach($json->articles as $articles){
echo $articles->name;

I want select only that name where id is 1.


You can use array_filter to get every item in the array with the id you want.

$id = 1;  // define your id

// filter for that id
$results = array_filter($json->articles, function($x) use ($id) {
    return $x->id == $id;

The result will be an array with zero or more elements, depending on how many times the id is found. I'm not sure what you need to do with the results, but you can loop over them with foreach, or access specific elements by key like this:

echo $results[0]->name;   // echo the name of the first match