2017-07-31 78 views
1

我使用PDO從數據庫中獲取數據,並且我需要幫助循環瀏覽PHP中的對象和子對象。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> 
+3

是的,這是可能的。 –

+0

你從哪裏得到這個'DB'對象?它的所有屬性都是私有的。它是來自框架嗎? –

+0

@不要恐慌我有兩個類:DB類執行所有查詢並將數據返回到執行其他任務的Software類。另外,DB類在Software類中被調用。 – Redzoua

回答

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>