Home > Backend Development > PHP Tutorial > How to Dynamically Generate an HTML Table from a PHP Array?

How to Dynamically Generate an HTML Table from a PHP Array?

DDD
Release: 2024-11-30 06:40:11
Original
781 people have browsed it

How to Dynamically Generate an HTML Table from a PHP Array?

How to Create a Dynamic HTML Table from a PHP Array

Generating HTML tables from PHP arrays is a common requirement. Let's explore how to accomplish this with a specific scenario in mind.

Creating a Table with Headings and Data

Suppose we have an array named $shop with the following structure:

$shop = array(
    array("rose",   1.25, 15),
    array("daisy",  0.75, 25),
    array("orchid", 1.15, 7 ),
); 
Copy after login

To create a table from this array, we can use the following steps:

1. Prepare the Data

It's preferable to modify the array structure by adding column names as keys:

$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) 
); 
Copy after login

2. Generate HTML

We can use PHP loops and the implode() function to generate the table markup:

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; ?>
Copy after login

Result

This code will generate a valid HTML table with the data from the $shop array, including the specified headings of "title", "price", and "number".

The above is the detailed content of How to Dynamically Generate an HTML Table from a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template