将mysql数据分类到单独的html表中?

时间:2011-03-09 08:49:10

标签: php mysql arrays foreach

我有一个返回ItemID,ItemName,CategoryID和CategoryName的数据库查询。我试图通过他们的CategoryName将我的结果分组到单独的html表中,因此最终结果看起来像这样:

 ________________________________
|____________CategoryName________|
| ItemName |                     |
|__________|                     |
| ItemName |                     |
|__________|                     |
| ItemName |                     |
|__________|_____________________|
 ________________________________
|____________CategoryName________|
| ItemName |                     |
|__________|                     |
| ItemName |                     |
|__________|                     |
| ItemName |                     |
|__________|_____________________|

目前我可以将我的数据输出到一个表中,但我不确定如何处理其余的表。 似乎我有比php技能更好的ascii艺术技巧:/

3 个答案:

答案 0 :(得分:0)

按CategoryName对数据进行排序,然后开始循环。在循环中,为第一个表写入起始HTML并开始逐行输出,但在每行检查CategoryName之前 - 如果它已更改,则关闭当前表并启动新表。

答案 1 :(得分:0)

HTML已关闭,但这应该让您入门:

<?php

$query = 'SELECT CategoryID, CategoryName, ItemID, ItemName
FROM tableName
ORDER BY CategoryID';

$result = mysql_query($query);
if (!$result || mysql_num_rows($result) == 0) {
    echo "No rows found";
    exit;
}

$lastCatID = 0; //or some other invalid category ID

while ($row = mysql_fetch_assoc($result)) {
    if($lastCatID != $row['CategoryID']) {
        //starting a new category
        if($lastCatID != 0) {
            //close up previous table
            echo '</table>';
        }

        //start a new table
        echo '<table><th><td colspan="2">Category '
                . $row['CategoryName'] .'</td></th>';
        $lastCatID = $row['CategoryID'];
    }

    echo '<tr><td>' . $row['ItemName'] . '</td><td></td></tr>';
}

if($lastCatID != 0) {
    //close up the final table
    echo '</table>';
}

mysql_free_result($result);
?>

答案 2 :(得分:0)

我更喜欢与foreach合作 - 就像这样:

$query = "SELECT CategoryID, CategoryName, ItemID, ItemName
FROM tableName
ORDER BY CategoryID";

$result = mysql_query($query);
if (!$result || mysql_num_rows($result) == 0) {
    echo "No rows found";
    exit;
}

$rows = mysql_fetch_assoc($result);

// create an array with the data structure closest to the HTML 
foreach( $rows as $row){
    $cats_data[$row['CategoryID']]['CategoryName'] = $row['categoryName'] ;
    $cats_data[$row['CategoryID']]['Items'][] = $row['ItemName'] ;
}

// Iterate through each category
foreach ( $cats_data as $category ) {
     echo '<table>';

     // echo out the table header
     echo '<tr><td>Item List for '.$category['CategoryName'].'</td></tr>' ;

     // Iterate through all the items in eaceh category
     foreach( $category['items'] as $item ) {
           echo '<tr><td>'.$item.'</td></tr>';
     }

     echo '</table>';
}

// cleanup
mysql_free_result($result);

对我来说感觉简单得多:)