I want to make a foreach loop in my json
decode script. I'm getting the info of an url, but that url has dynamic script, sometimes there are 4 results and sometimes 10 results.
I have these now:
<?php
$json = file_get_contents('URL');
$data = json_decode($json,true);
?>
<strong>Number</strong></a> <?php echo $data['Data'][1]['data']; ?><br />
I have now id 1 in my script, but i want alle the id's in my script. Is this possible with foreach oid ?
Else i have to make more rules.
<strong>Number</strong></a> <?php echo $data['Data'][1]['data']; ?><br />
<strong>Number</strong></a> <?php echo $data['Data'][2]['data']; ?><br />
<strong>Number</strong></a> <?php echo $data['Data'][3]['data']; ?><br />
I googled and checked Stack Overflow but I cant find the solution to my problem.
My Answer:
php
$url = "https://example.com/api";
$data = file_get_contents($url);
$results = json_decode($data, true);
foreach ($results as $result) {
// Do something with each result
echo $result['name'] . "
";
echo $result['age'] . "
";
echo $result['city'] . "
";
echo "
";
}
?>
This code will loop through each result in the JSON data and output the name, age, and city of each result. It will work for any number of results in the JSON data.
Rate this post
5 of 5 based on 1686 votesComments