Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP two dimensional array into HTML

A simple Google search will reveal a multitude of solutions for converting a two dimension array into HTML using PHP. Unfortunately none of these has the answers I am looking for.

I want a generic piece of code that converts an array into a HTML table. Where most examples go wrong is that they assume the programmer knows the name of the table's fields . I want this code to be generic such that I can use it even if I do not know the name of the fields.

I can see I need two loops. One nested inside of the other. What I am not sure of is how to get the values out given I don't know the keys.

The end result will hopefully output html something like this:

<th>
  <td>x/y</td>
  <td> x1 </td>
  <td> x2 </td>
</th>
<tr>
  <td>y1</td>
  <td> x1y1 </td>
  <td> x2y1 </td>
</tr>
<tr>
  <td>y2</td>
  <td> x1y2 </td>
  <td> x2y2 </td>
</tr>

Please remember I want a generic and simple solution. I hope this is clear.

like image 543
Brett Avatar asked May 13 '12 11:05

Brett


1 Answers

The following code will look through the two dimensions of the array and make them into a table. Regardless of what the key may be, you will get a visual representation of it. If they do have key name and not just an index, the values will be available in $key and $subkey respectively. So you have them if you need them.

The code:

$myarray = array("key1"=>array(1,2,3,4),
                 "key2"=>array(2,3,4,5),
                 "key3"=>array(3,4,5,6),
                 "key4"=>array(4,5,6,7)); //Having a key or not doesn't break it
$out  = "";
$out .= "<table>";
foreach($myarray as $key => $element){
    $out .= "<tr>";
    foreach($element as $subkey => $subelement){
        $out .= "<td>$subelement</td>";
    }
    $out .= "</tr>";
}
$out .= "</table>";

echo $out;

The result:

enter image description here

If you want to see the keys as headings, you could add this code after the echo "<table>"; line:

echo "<tr>";
foreach($myarray as $key => $element) echo "<td>$key</td>";
echo "</tr>";

Resulting in this:

enter image description here

like image 200
Juan Cortés Avatar answered Sep 30 '22 19:09

Juan Cortés