PHP:通过多维对象循环

时间:2017-07-31 21:33:08

标签: php oop

我使用PDO从数据库中获取数据,我需要帮助在PHP中循环对象和子对象。

我有一个看起来像这样的对象:

array (size=2)
  0 => 
    object(stdClass)[5]
      public 'id' => string '5' (length=1)
      public 'title' => string 'Google Chrome' (length=13)
      public 'slug' => string 'google-chrome' (length=13)
      public 'content' => string 'Download Chrome browser for free.....' (length=37)
      public 'excerpt' => string '' (length=0)
      public 'logo' => null
      public 'status' => string 'draft' (length=5)
      public 'views' => string '0' (length=1)
      public 'category_id' => string '0' (length=1)
      public 'created_at' => string '2017-06-12 16:59:22' (length=19)
      public 'updated_at' => string '2017-06-12 16:59:22' (length=19)
  1 => 
    object(stdClass)[10]
      public 'id' => string '6' (length=1)
      public 'title' => string 'Avast' (length=5)
      public 'slug' => string 'avast' (length=5)
      public 'content' => string 'Avast antivirus is ......' (length=25)
      public 'excerpt' => string 'excerpt....' (length=11)
      public 'logo' => null
      public 'status' => string 'published' (length=9)
      public 'views' => string '0' (length=1)
      public 'category_id' => string '0' (length=1)
      public 'created_at' => string '2017-06-12 17:45:18' (length=19)
      public 'updated_at' => string '2017-06-12 17:45:18' (length=19)

是否可以循环显示结果并将其显示在表格中? 是否可以循环结果并将其显示在表格中?

<table style="width:100%">
  <tr>
    <th>ID</th>
    <th>Title</th>
    <th>Status</th>
  </tr>
  <tr>
    <td>5</td>
    <td>Google Chrome</td>
    <td>draft</td>
  </tr>
  <tr>
    <td>6</td>
    <td>Avast</td>
    <td>published</td>
  </tr>
</table>

1 个答案:

答案 0 :(得分:0)

<?php
function html($text) {
    return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

// php template

<table style="width:100%">
    <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Status</th>
    </tr>
    <?php foreach ($rows as $row): ?>
        <tr>
            <td><?= html($row->id) ?></td>
            <td><?= html($row->title) ?></td>
            <td><?= html($row->status) ?></td>
        </tr>
    <?php endforeach; ?>
</table>