0
I have the following JSON variable resulting from a php query:
$json_string = '[
{
"id": 1,
"name": "Jogos para PC",
"products": [
{
"id": 34,
"name": "Grand Theft Auto V"
},
{
"id": 59,
"name": "Bloodstained Ritual of the Night"
},
{
"id": 60,
"name": "F1 2019 - Anniversary Edition"
},
{
"id": 62,
"name": "PLAYERUNKNOWN\'S BATTLEGROUNDS"
},
{
"id": 64,
"name": "Batman: Arkham Knight"
}
],
"tags": []
},
{
"id": 2,
"name": "Jogos Mobile",
"products": [
{
"id": 3,
"name": "Clash of Clãs"
},
{
"id": 4,
"name": "Mobile Legends"
}
],
"tags": []
},
{
"id": 4,
"name": "PlayStation Store",
"products": [
{
"id": 39,
"name": "PSN Gift Card - R$ 30,00"
},
{
"id": 40,
"name": "PSN Gift Card - R$ 60,00"
}
],
"tags": []
}
]';
I use the command $array = json_decode($json_string);
to work with the following code:
$array = json_decode($json_string);
foreach ($array as $value)
{
for ($row = 0; $row < 5; $row++) {
echo $value->products[($row)]->name .' - ID: '. $value->products[($row)]->id .'<br>';
}
}
This returns me the names of the games as follows:
Grand Theft Auto V - ID: 34<br>
Bloodstained Ritual of the Night - ID: 59<br>
F1 2019 - Anniversary Edition - ID: 60<br>
PLAYERUNKNOWN'S BATTLEGROUNDS - ID: 62<br>
Batman: Arkham Knight - ID: 64<br>
Clash of Clãs - ID: 3<br>
Mobile Legends - ID: 4<br>
I used $row < 5
because I know that the largest amount of games in one of the lists is 5, so all appear, the problem is when the list has less than 5 games because PHP returns an error:
Therefore, considering that he did not know the amount of games in each of the sets, what would be the correct way to list all the games in the array?
It doesn’t have to be exactly with 'for', this was the closest way to get where I need to go, so I used the question.
– Wesley