2017-10-11 49 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

我会在休息后显示数组 –