foreach 中的 php foreach
我想要实现的是能够像这样打印结果:
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 包装类,据我所知,我别无选择,只能使用“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.
我一直在尝试其他一些方法,但没有运气,希望有人会发现我的代码中的问题并引导我走向正确的方向。
预先感谢您,圣诞快乐。
What I am trying to achieve is to be able to print the result like this:
Header 1
Link 1
Link 2
Header 2
Link 3
Header 3
Link 4
Link 5
But the codes below is printing the result like this:
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
Using the php pdo wrapper class, as far as I know I have no choice but to use "foreach" instead of "while" to loop results, and here is my code:
$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.
I have been trying few other methods with no luck, hopefully someone will spot the problem in my code and lead me to the right direction.
Thank you in advance and Merry Christmas.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要在此行之前重置 $link_row:
foreach($linkQry AS $LinkRes)
You need to reset $link_row just before this line:
foreach($linkQry AS $LinkRes)
在第二次循环之前清空
$link_row
。empty
$link_row
before 2nd loop.