-1

I make an API request with PHP and the $data variable that comes back looks like the following:

[{
    "Id": 1,
    "Name": "AFC"
}, {
    "Id": 3,
    "Name": "RFC"
}, {
    "Id": 4,
    "Name": "CFC"
}, {
    "Id": 5,
    "Name": "LFC"
}, {
    "Id": 7,
    "Name": "MUFC"
}]

I want to know, how do I use a foreach loop to display a list of the titles?

Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190

2 Answers2

2

After the API request, your $data variable contains a JSON string.

Use json_decode to convert the string into an array, and the foreach loop construct to iterate over array:

$json_object = json_decode($data) ;

echo '<table>' ;
foreach ( $json_object as $child ) {

    echo '<tr>' ;
    echo '<td>' . $child -> Id. '</td>' ;
    echo '<td>' . $child -> Name . '</td>' ;
    echo '</tr>' ;

}
echo '</table>' ;
sammysaglam
  • 433
  • 4
  • 9
1
<?php 
foreach($data as $row){
echo $row["Id"];
echo "<br>";
echo $row["Name"];
}
Osama
  • 2,912
  • 1
  • 12
  • 15