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

时间:2013-09-14 00:34:35

标签: 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;
}

感谢您的时间。

2 个答案:

答案 0 :(得分:1)

此单个查询连接两个表,因此它仅返回lcategories中具有匹配项的Files行。它按parentpageID排序,与类别ID相同,因此同一类别中的所有行将在结果中一起显示。然后,当此ID更改时,fetch循环会通知,并在此时打印类别标题。

$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";

答案 1 :(得分:0)

使用if条件,并continue跳过,让你的循环跳到下一次。

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>';

// no like, so skip.
if (''==DST.$t_links['ImagePath'].DS.$t_links['referring_url']) continue;
print<<<END