简体   繁体   中英

Populate HTML table through PHP

I am looking for a way, to populate an HTML table through PHP when the HTML document is loaded.

I have a php file which creates the required table data:

echo <table id="mytable" ... </table>

The output of this PHP script should be written into the html file during its loading time.

Is there any way to accomplish this? Maybe through JavaScript?

This will get you started

<table>
  <thead>
    <tr>
      <th>Row One</th>
      <th>Row Two</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach( $array as $key ) { ?>
    <tr>
      <td><?php echo $key[ 'rowOne' ]; ?></td>
      <td><?php echo $key[ 'rowTwo' ]; ?></td>
    </tr>
  <?php } ?>
  </tbody>
</table>

You loop through each row in your array and echo out the information you need. You really need to do some PHP tutorials and you will understand how to loop arrays.

If you have data that is stored in row-major order (that is, your data is an array of rows, rather than columns, of data), you must keep track of the columns to print. This is a typical way to receive data from a MySQL database.

You can do this by looking at your first row, using $columns = array_keys($row) , or simply hard-code the column keys if they are known in advance like I have done in the following example.

<?php

$data = [
    [
        "name"  => "Alice",
        "email" => "alice@example.com",
        "home_address" => "Alice Lane 61"
    ],
    [
        "name"  => "Bob",
        "age"   => 16,
        "home_address" => "Bob St. 42"
    ]
];

$columns = [ "name", "age", "email", "home_address" ];

?>
<html>
<body>
<table>
    <tr>
        <?php foreach($columns as $column) { ?>
            <th><?php echo $column; ?></th>
        <?php } ?>
    </tr>
    <?php foreach ($data as $row) { ?>
        <tr>
            <?php foreach($columns as $column) { ?>
                <td>
                    <?php 
                        if (isset($row[$column])) {
                            echo $row[$column];
                        } else {
                            echo "N/A";
                        }
                    ?>
                </td>
            <?php } // end $column foreach ?>
        </tr>
    <?php } // end $row foreach ?>
</table>
</body>
</html>

Note that not all rows have the same columns here. This is handled in the if-statement in the table.

This example outputs:

 <html> <body> <table> <tr> <th>name</th> <th>age</th> <th>email</th> <th>home_address</th> </tr> <tr> <td>Alice </td> <td>N/A </td> <td>alice@example.com </td> <td>Alice Lane 61 </td> </tr> <tr> <td>Bob </td> <td>16 </td> <td>N/A </td> <td>Bob St. 42 </td> </tr> </table> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM