简体   繁体   English

PHP中的重复列

[英]Repeated column in PHP

$course = mysql_query('SELECT cc.name, c.fullname FROM mdl_course WHERE cc.id = c.id');

echo '<table>';
while($row = mysql_fetch_array($course))
{
     $categoryname = $row['name'];
     $coursename   = $row['fullname'];
     echo '<tr><td>$categoryname</td>
               <td>$coursename</td>
           </tr>
}
echo '</table>';

I want the category name to display only once ie, it shouldn't repeat 我希望类别名称仅显示一次,即不应重复

Some possible answers are already given. 已经给出了一些可能的答案。 My idea was to keep a counter variable too to check and see if it is the first iteration. 我的想法是也保留一个计数器变量,以检查它是否是第一次迭代。 If so, then show the category name. 如果是这样,则显示类别名称。

But besides of that i really think you should re-check your database design. 但是除此之外,我真的认为您应该重新检查数据库设计。 Why does multiple rows have the same category name? 为什么多行具有相同的类别名称? That is wrong in terms of database design. 就数据库设计而言,这是错误的。 The category should be in a sepparate table. 类别应在单独的表中。

That way you can loop through the categories first, echo the category name, then loop through the mdl_course table and get all the rows where the pk_category_id equals the fk_category_id from the mdl_course table. 这样,您可以首先遍历类别,回显类别名称,然后遍历mdl_course表,并获取mdl_course表中pk_category_id等于fk_category_id的所有行。

Example: 例:

$cats = query ("SELECT pk_category_id, name FROM categories");
while ( $cat_row = mysql_fetch_row($cats) )
{
    echo $cat_row['name'];

    $cats = query ("SELECT cols, you, need FROM mdl_course WHERE fk_category_id = '".$cat_row['pk_category_id']."'");
    while ( $mdl_row = mysql_fetch_row($cats) )
    {
        echo 'other data';
    }
}

You should add a temp var to save the previous category name, and print it only if it has changed. 您应该添加一个temp var来保存以前的类别名称,并仅在更改后才打印。 Note: this solution assumes your query results are grouped by categoryname 注意:此解决方案假定您的查询结果按类别名称分组

Like this: 像这样:

$course = mysql_query('SELECT cc.name, c.fullname FROM mdl_course WHERE cc.id = c.id');

echo '<table>';
$prev_name = ''; //temp var
while($row = mysql_fetch_array($course))
{
     $categoryname = $row['name'];
     $coursename   = $row['fullname'];
     echo '<tr><td>'.($prev_name != $categoryname ? $categoryname : '').'</td>
               <td>$coursename</td>
           </tr>';
     $prev_name = $categoryname; //temp var assignment
}
echo '</table>';

this snippet will check if the category name has changed, and give an appropriate output (the new category name or an empty string): 该代码段将检查类别名称是否已更改,并提供适当的输出(新的类别名称或空字符串):

($prev_name != $categoryname ? $categoryname : '')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM