【问题标题】:php grouped table sorting 1 offphp分组表排序1
【发布时间】:2012-04-09 16:23:04
【问题描述】:

我正在尝试通过 php 从 mysql 表中实现带有节分隔符的排序列表,但遇到了一些麻烦。我没有像我想要的那样把汤放在汤头里,而是把它放在下面的头里(就像我不想要的那样)!

这是视觉输出:

2-Soup
3-Salad
    2   Soup     Demo: Tom KaKai
4-Entree
    3   Salad    Demo: Spinach Salad
    4   Entree   Demo: Pork Chop
    4   Entree   Demo: Spicy Topped Shrimp

这是我的代码:

 $cat = null;
while($row = mysql_fetch_array($result))
{
    if( $row['catnum'] != $cat )
    {
        echo '<h1>' . $row['catnum'] . '-' . $row['ctgry'] . '</h1>';
        $cat = $row['catnum'];
    }
   echo "<table><tr><td>" . $row['catnum'] . " </td><td>" . $row['ctgry'] . "</td><td> " . $row['Shrt_Desc'] . "</td></tr>";
}

【问题讨论】:

  • 你看过源码了吗?您在循环中有一个打开的表标签,但没有关闭标签。还有什么问题?
  • 不确定这是否是您问题的答案,但您在 every 循环迭代中创建一个新表,而不是关闭您的 table 标记,因此每次循环迭代,您正在最后一个表中创建另一个表。这可能与它有关。我假设您只想为每个新标题创建一个新表,并将同一类别中的每个条目的行添加到该表中。

标签: php mysql while-loop grouping


【解决方案1】:

您没有关闭您的 &lt;table&gt; 标记,而是为检索到的每个 DB 行创建一个新表,因此在结构上您的 HTML 页面完全是一团糟。

你会想要这样的:

$first = true;
while ($row = mysql_fetch_array($result)) {
    if ($row['catnum'] != $cat) {
       if (!$first) {
           echo '</table>'; // close the table if we're NOT the first row being output.
       }

       $first = false; // no longer the first table, so disable this check.
       echo '<h1> etc...';
       echo '<table>'; // start new table
       $cat = $row['catnum'];
    }
    echo '<tr><td>' etc.... // output a table row
}

当您更改类别时,此代码只会输出 &lt;table&gt;&lt;h1> 内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多