2

Suppose that I have the following JSON file:

{
  "item_a_id":{
    "title":"...",
    "description":"..."
  },
  "item_b_id":{
    "title":"...",
    "description":"..."
  }
}

I use the json_decode() function to create an array, which will be later used to create a table with every item and its respective properties, preferably in the following format:

ID        | Title        | Description        |
----------|--------------|--------------------|
item_a_id | item_a_title | item_a_description |
item_b_id | item_b_title | item_b_description |

For this, I have written the following PHP code:

// Load JSON data into array
$items = json_decode ($json_string, true);

// Begin the HTML table
echo "<table>";

// Add a row with information of each item
foreach ($items as $item) {
  echo "<tr>";
  echo "<td>" . "ID should go here..." . "</td>";
  echo "<td>" . $item['title'] . "</td>";
  echo "<td>" . $item['description'] . "</td>";
  echo "</tr>";
}

// End table
echo "</table>";

While the title and description of every item is loaded correctly, I cannot seem to find a way to get the item ID. Is there a way to get the 'name' of the 'root' key of an array in PHP?

Alex Spataru
  • 1,197
  • 4
  • 14
  • 26

1 Answers1

1

The foreach pattern to get the key and value is as follows:

foreach ($items as $key => $value){
   echo "<tr>";
   echo "<td>" . $key  . "</td>";
   echo "<td>" . $value['title'] . "</td>";
   echo "<td>" . $value['description'] . "</td>";
   echo "</tr>";
}
Phiter
  • 14,570
  • 14
  • 50
  • 84