php-sql对具有相同类别的数据进行分组

时间:2012-07-23 08:24:20

标签: php sql categories

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

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

但是又一次,我希望它在单独的表格中。

1 个答案:

答案 0 :(得分: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>";

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