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

$current_cat が前のループ $current_cat と等しいかどうかをテストする if ステートメントを追加できます。これを行うには、新しい変数 $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 に答える