Reputation:
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 text
variable of the entry with (for example) id
being 37
in PHP? Is it possible to get that easily?
What I know: I could use a for loop for finding the 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, as my JSON array has more than 3 entries, and if i request a lot of data in short time it takes long time till the for loop goes through every entry. So is there a more effective way to get to the same result? Can somebody explain me this in PHP?
Upvotes: 5
Views: 87
Reputation: 5899
The solution with array_filter()
:
$yourEntry = current(array_filter($jsonArray, function(\stdClass $entry) {
return ($entry->id == 37);
}));
Upvotes: 1
Reputation: 242
Are you in control of the json data structure? If so, you could change to access via array key, e.g.
{
'37': 'pear',
'45': 'apple',
'22': 'strawberry'
}
$fruits = json_decode(file_get_contents("file.json"), true);
echo $fruits['37']; // pear
Upvotes: 0
Reputation: 2625
if you can change your json structure then it 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 :)
Upvotes: 0
Reputation: 2817
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 intend to use for loop only then 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
}
}
?>
Upvotes: 0