Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make a table with an associative array (PHP)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading