php - 如何在 PHP while 循环中隐藏没有 url 的类别

标签 php mysql

我需要隐藏所有没有链接的类别。基本上,我所拥有的是所有可能的类别和每个类别的唯一 ID 的表,第二个表包含为每个小部件分配了父页面 ID 的所有小部件。父页面 ID 是相关类别项目的 ID(名称,如果您愿意的话)。

现在我的问题是,使用下面可以看到的脚本,一切正常,除了一件事之外,所有类别项都会显示,即使它们中没有链接,我确实理解原因,但无法弄清楚解决所有问题的方法。

请帮忙

    $category_topic_query = 'SELECT * FROM lcategories ORDER BY ID asc';
    $resc = $db->prepare($category_topic_query);
    $resc->execute();
    $template_link_query = "SELECT parentpageID, ImagePath, referring_url, templateTitle FROM Files WHERE parentpageID = :id AND pageID = '0'";
    $link_res = $db->prepare($template_link_query);

while ($category_topic = $resc -> fetch()){
    $category_topic_ID = $category_topic['ID'];
    $category_topic_name = str_replace("&", "&", $category_topic['category_name']);
    $category_topic_url = DST.$category_topic['category_folder'].DS.$category_topic['category_page'];
    $link_res->execute(array(':id' => $category_topic_ID));


print<<<END
<h3><a href="$category_topic_url">$category_topic_name</a></h3>
<ul class="arrow">

END;

while ($t_links = $link_res -> fetch()){
    $templateID = $t_link['parentpageID'];
    $links_array = '<li><a href="'.DST.$t_links['ImagePath'].DS.$t_links['referring_url'].'">'.$t_links['templateTitle'].'</a></li>';

print<<<END
$links_array

END;
}
print<<<END
</ul>

END;
}

感谢您的宝贵时间。

最佳答案

此单个查询连接两个表,因此它仅返回在 Files 中具有匹配项的 lcategories 行。它按 parentpageID 排序,该 ID 与类别 ID 相同,因此同一类别中的所有行都将出现在结果中。然后,获取循环会注意到此 ID 何时发生变化,并在那时打印类别 header 。

$query = "SELECT l.category_name, l.category_folder, l.category_page,
                 f.parentpageID, f.ImagePath, f.referring_url, f.templateTitle
          FROM lcategories l
          INNER JOIN Files f ON f.parentpageID = l.ID
          WHERE f.pageID = '0'
          ORDER BY f.parentpageID";
$stmt = $db->prepare($query);
$stmt->execute();
$last_topic = null;
$first_row = true;
while ($row = $stmt->fetch()) {
    $category_topic_ID = $row['parentpageID'];
    if ($category_topic_ID !== $last_topic) {
        $category_topic_name = htmlentities($row['category_name']);
        $category_topic_url = DST.$row['category_folder'].DS.$row['category_page'];
        if (!$first_row) {
            print "</ul>\n;";
            $first_row = false;
        }
        print<<<END
<h3><a href="$category_topic_url">$category_topic_name</a></h3>
<ul class="arrow">

END;
        $last_topic = $category_topic_ID;
    }
    $links_array = '<li><a href="'.DST.$row['ImagePath'].DS.$row['referring_url'].'">'.$row['templateTitle'].'</a></li>';

    print<<<END
    $links_array

    END;
}
print "</ul>\n";

关于php - 如何在 PHP while 循环中隐藏没有 url 的类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18797133/

相关文章:

php - 从数据库字段中删除特定的 id

php - sql multi query 可以被认为是原子指令吗?

php - 带有迭代器接口(interface)的嵌套 foreach

php - 在函数范围外引用变量的更好方法是什么?

php - 如何在 Opencart 中添加子选项?

mysql - Multi Subquery count函数无法承受多重选择的压力

php - SUM 查询或遍历对象数组并对数据成员求和会更有效吗?

从选择加入更新 MYSQL

php - 为什么我的博客发不了?

php - 在 Laravel 中返​​回带有参数的 View