2017-10-11 84 views
0

我目前正在使用php的Table類。此類僅通過爲所選數據的列名和數組賦值來創建動態表。我被困在以我想要的正確方式顯示值。這就是它現在的樣子:current table。我認爲這可能是我的陣列。在數組中,所有的值都是這樣的:array。第二個在第一個id之前。這裏是我的表類:動態表不能顯示數組值正確

public function displayTable($columns, $values = 0) 
    { 

     $this->setTable("<table class='table table-striped table-hover'> 
         <thead class='thead-inverse'> 
          <tr>"); 



     foreach ($columns as $columnName) { 
      $this->setTable($this->getTable(). "<th>".$columnName."</th>"); 
     } 



     $this->setTable($this->getTable(). "</tr></thead><tbody>"); 


     for ($x = 0; $x != sizeof($values); $x++) { 
      $this->setTable($this->getTable(). "<tr>"); 

      foreach ($values as $value) { 
       $this->setTable($this->getTable(). "<td>".$value[$x] ."</td>"); 
       var_dump($value); 
      } 

      $this->setTable($this->getTable(). "</tr>"); 
     } 

     $this->setTable($this->getTable(). "</tbody></table>"); 

     var_dump($this->getTable()); 
    } 

我試着在我的選擇查詢中應用一個訂單。這將擺脫陣列上我的問題。在td中正確顯示項目是個問題。 td是不斷創建的,直到它沒有任何值,並開始一個新的數組,就像我在圖片中展示的那樣。那麼無論如何要解決在表頭td下顯示這些值的問題嗎?

+1

而是使得「神奇HTML生成器」級的,你應該有使用[本地模板](http://chadminick.com/articles/simple-php-template-engine.html)或[Twig](https://twig.symfony.com/)之類的東西。 –

+1

問題是你使用'fetch_array()'來獲取給你數字+關聯數組combo的記錄。使用'fetch_assoc()'使第二個foreach能夠完美工作。 –

+0

好吧,我將我的fetchAll()更改爲:fetchAll(PDO :: FETCH_ASSOC)。這沒有做到。我可以嘗試將其更改爲FETCH_NUM –

回答

0

通過查看您的陣列圖像,似乎您使用fetchAll()從數據庫中獲取記錄。

fetchAll()組合提供數字+關聯數組。這就是爲什麼你的記錄來是這樣的: -

array(
    'userId'=>2, 
    0=>2, 
    'userEmail'=>'some value', 
    1=>'same mail id' 
); 

現在你只有兩個theads # and email,但第二次的foreach每次迭代後,爲您提供4 <td>,並hense表失真。

解決方案: -你必須使用fetchAll(PDO::FETCH_NUM)解決您的問題,之後更改您的代碼如下圖所示: -

public function displayTable($columns, $values = 0){ 

    $this->setTable("<table class='table table-striped table-hover'><thead class='thead-inverse'><tr>"); 

    foreach ($columns as $columnName) { 
     $this->setTable($this->getTable(). "<th>".$columnName."</th>"); 
    } 

    $this->setTable($this->getTable(). "</tr></thead><tbody>"); 


    for ($x = 0; $x != sizeof($values); $x++) { 
     $this->setTable($this->getTable(). "<tr>"); 

     foreach ($values as $key=> $value) { 
      $this->setTable($this->getTable(). "<td>".$value[$key] ."</td>"); 
     } 
     $this->setTable($this->getTable(). "</tr>"); 
    } 

    $this->setTable($this->getTable(). "</tbody></table>"); 

    var_dump($this->getTable()); 
} 
+0

Wel我嘗試了我的fetchAll上的PDO :: FETCH_ASSOC。這並沒有解決問題。在我的第二個foreach中,我使用$ x來遍歷$ value的值並使用assoc給我一個錯誤。 –

+0

謝謝。仍然一切都是這樣的:首先是沒問題的。比第一個tr如下1 2和比下一個第一個電子郵件,第二個電子郵件。我特意想顯示ID下的#和電子郵件下的電子郵件 –

+0

我會在休息後顯示數組 –