在foreach内的php foreach

时间:2011-12-25 03:16:42

标签: php loops foreach pdo

我想要实现的是能够打印出这样的结果:

Header 1
    Link 1
    Link 2
Header 2
    Link 3
Header 3
    Link 4
    Link 5

但下面的代码是打印结果:

Header 1
    Link 1
    Link 2
Header 2
    Link 1
    Link 2
    Link 3
Header 3
    Link 1
    Link 2
    Link 3
    Link 4
    Link 5

使用php pdo wrapper class,据我所知,我别无选择,只能使用“foreach”代替“while”循环结果,这是我的代码:

$bind = array(":users_id" => $id);
$categoryQry = $db->select("category","users_id=:users_id", $bind);
//loop Headers
foreach($categoryQry AS $CatRes){
    $category_name = $CatRes['category_name'];

    $bind = array(
        ":users_id" => $id,
        ":link_category" => $CatRes['category_id']
    );
    $linkQry = $db->select("links", "users_id=:users_id AND link_category=:link_category", $bind);
    //loop Links under each header
    foreach($linkQry AS $LinkRes){
        $link_url = $LinkRes['link_url'];
        //$link_row outputs the links under each header, this is where the problem is        
        $link_row .= DisplayLayout("link_row.html","\$link_url");
    }

    //$header outputs the result OK (3 headers as stated in above example)    
    $header .= DisplayLayout("header.html","\$category_name,\$link_row");
}
//note that DisplayLayout is my template function which is used for outputting variables using an HTML file.

我一直在尝试其他一些没有运气的方法,希望有人会在我的代码中发现问题并引导我走向正确的方向。

提前谢谢你,圣诞快乐。

4 个答案:

答案 0 :(得分:1)

$bind = array(":users_id" => $id);
$categoryQry = $db->select("category","users_id=:users_id", $bind);
//loop Headers
foreach($categoryQry AS $CatRes){
$category_name = $CatRes['category_name'];

$bind = array(
    ":users_id" => $id,
    ":link_category" => $CatRes['category_id']
);
$linkQry = $db->select("links", "users_id=:users_id AND link_category=:link_category", $bind);
//loop Links under each header
$link_row='';
foreach($linkQry AS $LinkRes){
    $link_url = $LinkRes['link_url'];
    //$link_row outputs the links under each header, this is where the problem is        
    $link_row .= DisplayLayout("link_row.html","\$link_url");
}

//$header outputs the result OK (3 headers as stated in above example)    
$header .= DisplayLayout("header.html","\$category_name,\$link_row");
}
//note that DisplayLayout is my template function which is used for outputting     variables using an HTML file.

答案 1 :(得分:1)

//reset linkrow
$link_row = '';


foreach($linkQry AS $LinkRes){
    $link_url = $LinkRes['link_url'];
    //$link_row outputs the links under each header, this is where the problem is        
    $link_row .= DisplayLayout("link_row.html","\$link_url");
}

答案 2 :(得分:1)

您需要在此行之前重置$ link_row:foreach($linkQry AS $LinkRes)

答案 3 :(得分:0)

在第二次循环之前清空$link_row