如何在RecursiveArrayIterator中打印表数据索引

时间:2016-11-14 14:46:36

标签: php html mysql pdo

我想打印一个带索引的表,我现在是PDO和递归表打印的新手(这就是所谓的?)。我找到了一个示例代码来执行此操作,但它没有将索引与数据一起打印。所以我修改了代码以包含索引。但是,我正在使用全局变量,根据我的理解,使用全局变量是一种不好的做法。是这样吗?还有其他办法吗?

<?php

      echo "<table id='DataTable1' class='display' cellspacing='0' width='100%'>";
      echo "<tr><th>No</th><th>Name</th><th>Phone</th><th>Email</th><th>Guest</th><th>Attendance</th></tr>";

      $i = 1;

      class TableRows extends RecursiveIteratorIterator { 

          function __construct($it) {
              parent::__construct($it, self::LEAVES_ONLY); 
          }

          function current() {
              return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
          }

          function beginChildren() { 
              $index = $GLOBALS['i'];
              echo "<tr><td>$index</td>"; 
          } 

          function endChildren() { 
              echo "</tr>" . "\n";
              $GLOBALS['i']++;
          } 
      } 

      try {
          $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
          $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
          $stmt = $conn->prepare("SELECT guestName, guestPhone, guestEmail, guestGuest, attendance FROM rsvp_list"); 
          $stmt->execute();

          // set the resulting array to associative
          $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
          foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { 
            echo $v;
          }
      }
      catch(PDOException $e) {
          echo "Error: " . $e->getMessage();
      }
      $conn = null;
      echo "</table>";
      ?>

1 个答案:

答案 0 :(得分:2)

最佳做法显然是根本不使用递归迭代器来输出HTML表格。一些奇怪的人把它放在网页上,出于某种原因,许多人开始让他们的生活变得十倍复杂。

在输出HTML表时,根本不需要迭代器,更不用说递归了。

<?php

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT guestName, guestPhone, guestEmail, guestGuest, attendance FROM rsvp_list";
$data = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC); 

?>
<table id='DataTable1' class='display' cellspacing='0' width='100%'>
    <tr><th>No</th><th>Name</th><th>Phone</th><th>Email</th><th>Guest</th><th>Attendance</th></tr>
    <? foreach ($data as $index => $row): ?>
        <tr>
            <td><?=$index+1?></td>
            <? foreach ($row as $value): ?>
                <td style='width:150px;border:1px solid black;'><?=$value?></td>
            <? endforeach ?>
        </tr>
    <? endforeach ?>
</table>

这段代码清洁,更短,更健全。