1
<?php
$q = mysql_query("SELECT sub_cat.*, links.*
                 FROM links
                 LEFT JOIN sub_cat
                 ON links.p_id = sub_cat.id
                 WHERE sub_cat.p_id = '$id'
                 ORDER BY name ASC") or die (mysql_error());

while ($r = mysql_fetch_assoc($q))
{
    $links_name = $r['name'];
    $link_h3 = $links_name != '' ? '<h3>' . $links_name . '</h3>' : '';
    //print $link_h3;
    print '<pre>';
    print_r ($r);
}
?>

我有两个表,其中的行如下:

子猫

  • ID
  • 姓名
  • p_id

链接

  • ID
  • 链接
  • p_id

在 sub cat 中,我有电影类别,如外语电影、国家电影、未分类电影等。在链接表中,我有具体的电影链接,具体取决于子类别。

唯一的事情是我不想要重复的标题(sub_cat.name)。结果是:

无类别www.movi​​esite.com

无类别www.movi​​esite2.com

无类别www.movi​​esite3.com

外国电影www.movi​​esite1.bla

外国电影www.movi​​esite2.bla

我想成为

无类别www.movi​​esite.com

www.movi​​esite2.com

www.movi​​esite3.com

外国电影www.movi​​esite1.bla

www.movi​​esite2.bla

并且不知道如何做到这一点:(

任何帮助表示赞赏。

4

2 回答 2

2

要完成这项工作,您有 2 个解决方案:

第一个解决方案是在显示之前处理您的数据,以便按类别对所有电影进行分组。

例如,您可以这样做:

$moviesByCategory = array();

while ($r = mysql_fetch_assoc($q))
{
    // Create the new sub array for the new category if necessary
    if (!isset($moviesByCategory[$r['name']]))
        $moviesByCategory[$r['name']] = array();

    // Add the movie in the category
    $moviesByCategory[$r['name']][] = $r['links'];
}

然后,您现在可以迭代这个新数组,例如

foreach($moviesByCategory as $category => $movies)
{
    // Print the category name
    echo '<h1>' . $category . '</h1>';

    // Print all movies of the category
    foreach($movies as $movie)
        echo '<h3>' . $movie . '</h3>';
}

第二种解决方案是修改 SQL 查询,将所有具有相同类别的电影直接分组。您只需要使用一个GROUP BY子句sub_cat.id,然后在选择中的所有其他字段上应用一个聚合函数。

就性能方面而言,最好的解决方案是 SQL 解决方案,但使用 PHP 执行此操作将为您提供更多的演示灵活性。

于 2013-05-20T00:32:24.673 回答
-1

尝试类似:

$lastSubcatName = "";
while ($r = mysql_fetch_assoc($q))
{
  $links_name = $r['name'];

  if($lastSubcatName != $links_name)
  {
    echo "<h1>".$links_name."</h1>";
    $lastSubcatName = $links_name;
  }

  echo '<h3>' . $r['links'] . '</h3>';
}
于 2013-05-20T00:23:43.093 回答