Output a php multi-dimensional array to a html table

后端 未结 3 2028
温柔的废话
温柔的废话 2020-12-06 14:26

I have a form that has 8 columns and a variable number of rows which I need to email to the client in a nicely formatted email. The form submits the needed fields as a multi

相关标签:
3条回答
  • 2020-12-06 15:06

    How about this?

    $keys = array_keys($_POST['order'][0]);
    echo "<table><tr><th>".implode("</th><th>", $keys)."</th></tr>";
    foreach ($_POST['order'] as $order) {
      if (!is_array($order))
        continue;
      echo "<tr><td>".implode("</td><td>", $order )."</td></tr>";
    }
    echo "</table>
    
    0 讨论(0)
  • 2020-12-06 15:07

    In your HTML, try something like this:

    <table>
    <tr>
      <th>Bottom</th>
      <th>Slant</th>
      <th>Fitter</th>
    </tr>
    <?php foreach ($_POST['order'] as $order): ?>
      <tr>
        <td><?php echo $order['bottomdiameter'] ?></td>
        <td><?php echo $order['slantheight'] ?></td>
        <td><?php echo $order['fittertype'] ?></td>
      </tr>
    <?php endforeach; ?>
    </table>
    

    Obviously, I'm not including all your attributes there, but hopefully you get the idea.

    0 讨论(0)
  • 2020-12-06 15:09

    A Table class I wrote some time ago

    <?php
    class Table {
        protected $opentable = "\n<table cellspacing=\"0\" cellpadding=\"0\">\n";
        protected $closetable = "</table>\n";
        protected $openrow = "\t<tr>\n";
        protected $closerow = "\t</tr>\n";
    
        function __construct($data) {
            $this->string = $this->opentable;
            foreach ($data as $row) {
                $this->string .= $this->buildrow($row);
            }
            $this->string .= $this->closetable;
        }
    
        function addfield($field, $style = "null") {
            if ($style == "null") {
                $html =  "\t\t<td>" . $field . "</td>\n";
            } else {
                $html = "\t\t<td class=\"" . $style . "\">"  . $field . "</td>\n";
            }
            return $html;
        }
    
        function buildrow($row) {
            $html .= $this->openrow;
            foreach ($row as $field) {
                $html .= $this->addfield($field);
            }
            $html .= $this->closerow;
            return $html;
        }
    
        function draw() {
            echo $this->string;
        }
    }
    ?>
    

    To be used like this :

    <body>
    <?php
    $multiDimArray = []; # Turn the form array into a matrix
    for ($i = 0; $i < count($_POST['order']); $i++) {
            $multiDimArray[] = [];
        foreach ($_POST['order'][$i] as $key=>$value) {
            if ($i == 0) {
                $multiDimArray[$i][] = $key;
            }
            $multiDimArray[$i][] = $value;
        }
    }
    
    $table = new Table($multiDimArray); # Create and draw the table
    $table->draw();
    ?>
    </body>
    
    0 讨论(0)
提交回复
热议问题