Make a table with an associative array (PHP)

Advertisements

Im trying to make a table in my app with the data from an array. This is my array (used var_dump to get it)

array(5) { [0]=> array(1) { ["A"]=> int(0) } [1]=> array(1) { ["B"]=> int(0) } [2]=> array(1) { ["C"]=> int(0) } [3]=> array(1) { ["D"]=> int(0) } [4]=> array(1) { ["E"]=> int(0) } }

This array is converted from a JSON that looks like this:

[{"A":0},{"B":0},{"C":0},{"D":0},{"E":0}]

I’m trying to make a table where each row is one "letter" (in this example), something like this

Column A Column B
A 0
B 0
C 0

I’ve tried using do-while loops, and also for loops.

>Solution :

The first thing you have to do is a for loop to get each element of the array and then for each array do another loop to get the $key and value example:

<table>
<tr>
  <th>Column A</th>
  <th>Column B</th>
</tr>
<?php
foreach ($letters as $columns) {
   echo '<tr>';
   foreach($columns as $column => $value) {
     echo '<td>' . $column . '</td>';
     echo '<td>' . $value . '</td>';
   }
   echo '</tr>';
}
?>
</table>

Leave a ReplyCancel reply