0

如何将我的提取行打印到数据组中?例如,我的数据库中有这些

title       category
one         number
two         number
three       number
a           letter
b           letter
c           letter

我想把它打印在另一张桌子上。

table1      table2
number      letter
one         a
two         b
three       c

这是我尝试过的。

$select = "SELECT * FROM `table` ORDER BY `category`";
$result = mysql_query($select);

$current_cat = null;

while ($rows = mysql_fetch_array($result)) 
    { 
        if ($rows["category"] != $current_cat) 
                    {
                        $current_cat = $rows["category"];
                        echo "<p>$current_cat</p>";
                    }
        echo"$rows[title]";
}   

这些代码的输出是这样的

number  
one
two
three

letter
a
b
c

但话又说回来,我希望它在单独的表中。

4

1 回答 1

2

您可以添加一个 if 语句来测试 $current_cat 是否等于前面的循环 $current_cat。通过添加一个新变量 $last_cat 来做到这一点,在 while 循环结束时将其设置为等于当前迭代 $current_cat。这是一个例子

   $select = "SELECT * FROM `table` ORDER BY `category`";
    $result = mysql_query($select);

    $current_cat = null;
    $last_cat = null;

    while ($rows = mysql_fetch_array($result)) { 

            if ($current_cat == null) {
        // Create a table with an id name of the first table
        echo "<table id='" . $rows["category"] . "'>";
// Write the first row of the table - Category Title
echo "<tr class='categoryTitle'><td>" . $rows["category"] . "</td></tr>";
        }

    // Set the $current_cat to current loop category value
         $current_cat = $rows["category"];

    if ($last_cat != null) {
            if ($current_cat != $last_cat) {
            // Close table from previous $current_cat
        echo "</table>";
        // Create new table with id name of the category
        echo "<table id='" . $rows["category"] . "'>";
// Write the first row of the table - Category Title
echo "<tr class='categoryTitle'><td>" . $rows["category"] . "</td></tr>";
        }
    }

                            }
// Write new row in table with the value of the title
                echo "<tr><td>" . $rows[title] . "</td></tr>";

    // set the $last_cat to the value of $current_cat at the end of the loop
    $last_cat = $current_cat;
    } 

    // Close the last table after while loop ends
    echo "</table>";

这将允许您根据类别名称创建单独的表格,无论您有多少类别,并允许您根据类别名称设置表格的样式。

于 2012-07-23T09:11:36.497 回答