【问题标题】:Extracting columns from sql table with php用php从sql表中提取列
【发布时间】:2017-09-14 15:11:51
【问题描述】:

我的查询从我的表中选择所有列

$spool = $wpdb->get_results('SELECT * FROM `tablename`');

然后我在表格中显示结果。我需要显示所有列。我就是这样做的。

echo "<table>";
  if ( !empty( $spool ) ) {
      echo  "<tr><th> header </th></tr>";
             foreach ( $spool as $a ) {
                    echo "<tr><th>" . $a->columnname1 . "</th><th>" .$a->columnnameN . "</th></tr>";
                }   

    }
echo "</table>";

现在我有大约 40 列,我想问一下是否有更智能且不那么繁琐的显示方式。

【问题讨论】:

  • 分享截图或小提琴
  • 对于 40 列,您想显示所有列,通常是 x 轴滚动表 div 。和压缩表,单元格中的填充更少等
  • 我的问题是一个 php 问题。不是为每个人都做 $a->columnname ,有没有更短的方法来编写它并仍然显示所有它们。
  • 我知道如果我为每一列都写 $a->columnname 可以将它们全部显示出来,但这会很乏味。
  • $a 的实例是什么?

标签: php mysql sql wordpress


【解决方案1】:

可能你需要嵌套循环,你得到的结果可能是这样的

array(
    0:{column1:test,column2:test . . . },
    1:{column1:test,column2:test . . . }
)

所以你可以试试这个方法

    echo "<table>";
    if ( !empty( $spool ) ) {
      echo  "<tr><th> header </th></tr>";
        foreach ( $spool as $key => $value  ) {
           echo '<tr>';
             foreach ( $value as $a ) {
                      echo "<th>" . $a. "</th>";
                 }   
            echo '</tr>';
          }
      }
      echo "</table>";

【讨论】:

    【解决方案2】:

    当您拥有对象时,您可以将它们转换为数组并使用 implode。 (但属性顺序可能与您想要的不同。)

    <?php
    class A
    {   
        public $foo = 'bing'; 
        public $bar = 'bang';
        public $baz = 'bong';    
    }
    $spool = [new A, new A];
    
    echo '<table>';
    foreach($spool as $a) {
        echo '<tr>';
        echo '<td>' . implode('</td><td>', (array) $a) . '</td>';
        echo '</tr>';
    }
    echo '</table>';
    

    输出:

    <table><tr><td>bing</td><td>bang</td><td>bong</td></tr><tr><td>bing</td><td>bang</td><td>bong</td></tr></table>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 2020-01-23
      相关资源
      最近更新 更多