Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a HTML Table from a PHP array?

Tags:

arrays

html

php

How do I create a HTML table from a PHP array? A table with heading as 'title', 'price', and 'number'.

$shop = array(     array("rose",   1.25, 15),     array("daisy",  0.75, 25),     array("orchid", 1.15, 7 ), );  
like image 262
ktm Avatar asked Jan 20 '11 10:01

ktm


People also ask

How do I make a table in PHP using HTML?

You can create a table using the <table> element. Inside the <table> element, you can use the <tr> elements to create rows, and to create columns inside a row you can use the <td> elements. You can also define a cell as a header for a group of table cells using the <th> element.


2 Answers

It would be better to just fetch the data into array like this:

<?php $shop = array( array("title"=>"rose", "price"=>1.25 , "number"=>15),                array("title"=>"daisy", "price"=>0.75 , "number"=>25),                array("title"=>"orchid", "price"=>1.15 , "number"=>7)               );  ?> 

And then do something like this, which should work well even when you add more columns to your table in the database later.

<?php if (count($shop) > 0): ?> <table>   <thead>     <tr>       <th><?php echo implode('</th><th>', array_keys(current($shop))); ?></th>     </tr>   </thead>   <tbody> <?php foreach ($shop as $row): array_map('htmlentities', $row); ?>     <tr>       <td><?php echo implode('</td><td>', $row); ?></td>     </tr> <?php endforeach; ?>   </tbody> </table> <?php endif; ?> 
like image 64
Richard Knop Avatar answered Sep 26 '22 06:09

Richard Knop


Here's mine:

<?php     function build_table($array){     // start table     $html = '<table>';     // header row     $html .= '<tr>';     foreach($array[0] as $key=>$value){             $html .= '<th>' . htmlspecialchars($key) . '</th>';         }     $html .= '</tr>';      // data rows     foreach( $array as $key=>$value){         $html .= '<tr>';         foreach($value as $key2=>$value2){             $html .= '<td>' . htmlspecialchars($value2) . '</td>';         }         $html .= '</tr>';     }      // finish table and return it      $html .= '</table>';     return $html; }  $array = array(     array('first'=>'tom', 'last'=>'smith', 'email'=>'[email protected]', 'company'=>'example ltd'),     array('first'=>'hugh', 'last'=>'blogs', 'email'=>'[email protected]', 'company'=>'example ltd'),     array('first'=>'steph', 'last'=>'brown', 'email'=>'[email protected]', 'company'=>'example ltd') );  echo build_table($array); ?> 
like image 37
GhostInTheSecureShell Avatar answered Sep 26 '22 06:09

GhostInTheSecureShell