PHP allows us to construct HTML tables from arrays, providing a convenient way to display tabular data. To generate a table with header labels 'title', 'price', and 'number', we proceed as follows:
The given PHP array in the question, $shop, represents the data for our table. However, for better organization, it's preferable to explicitly label each field with keys like "title", "price", and "number." This ensures clarity and simplifies table generation.
$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) );
With the data initialized correctly, we can proceed to build the HTML table:
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; ?>
The above is the detailed content of How to Generate HTML Tables from PHP Arrays?. For more information, please follow other related articles on the PHP Chinese website!