JSON: getting a record with a specific value

I have the following JSON array, in this case it has only three entries, but there could also be more.

[ { "id": 45, "text": "apple" }, { "id": 37, "text": "pear" }, { "id": 22, "text": "strawberry" } ] 

Now my question is: how do I get the variable text entries with (for example) id like 37 in PHP? Is it easy to do this?

What I know: I could use a for loop to find text like this (in PHP):

 <?php $fruits = json_decode(file_get_contents("file.json"), true); // First I decode the file for ($i = 0; $i < count($fruits); $i++) { // Using this for loop and if condition, I get the text I need if ($fruits[$i]['id'] == 37) echo $fruits[$i]['text']; } ?> 

But I don't want to use a for loop, since my JSON array has more than 3 records, and if I request a lot of data in a short time, it will take a long time until the for loop goes through each record. So is there a better way to get the same result? Can someone explain this to me in PHP?

+5
source share
5 answers

if you can change your json structure then this is possible.

If you create json like this

 { "45":{ "text": "apple" }, "37":{ "text": "pear" }, "22":{ "text": "strawberry" } } 

and in php

  echo $item['37']['text']; 

This will help :)

0
source

Solution with array_filter() :

 $yourEntry = current(array_filter($jsonArray, function(\stdClass $entry) { return ($entry->id == 37); })); 

See example

+1
source

Change this code:

 <?php $fruits = json_decode(file_get_contents("file.json"), true); // First I decode the file for ($i = 0; $i < count($fruits); $i++) { // Using this for loop and if condition, I get the text I need if ($fruits[$i]['id'] == 37) echo $fruits[$i]['text']; } ?> 

to

 <?php $fruits = json_decode(file_get_contents("file.json"), true); // First I decode the file foreach ($fruits as $fruit) { // Using this for loop and if condition, I get the text I need if ($fruits['id'] == 37) { echo $fruits['text']; //rest of your code you like to add } } ?> 

if you are going to use only for loop use below code:

 <?php $fruits = json_decode(file_get_contents("file.json"), true); // First I decode the file for ($i = 0; $i < count($fruits); $i++) { // Using this for loop and if condition, I get the text I need if ($fruits['id'] == 37) { echo $fruits['text']; //rest of your code you like to add } } ?> 
0
source

You can do it simply with this:

 foreach($fruits as $item) { if($item['id'] == 37) { echo $item['text']; break; } } 

Example

0
source

Do you control json data structure? If so, you can access using the array key, for example.

 { '37': 'pear', '45': 'apple', '22': 'strawberry' } 

$ fruits = json_decode (file_get_contents ("file.json"), true);

echo $ fruits ['37 ']; // pear

0
source

All Articles