是的,所以我有一个看起来像这样的查询:
$bestof_query = "SELECT * FROM physicians p JOIN (awards a, categories c, awardLevels l) ON (a.id = p.id AND c.id = a.category AND l.id = a.level) ORDER BY a.category, a.level ASC ";
$query = mysql_query($bestof_query);
while($result = mysql_fetch_array($query)) {
extract($result);
echo "<h3>" . $category . "<h3>";
foreach($category as $value) {
echo "<h5>" . $name . "<h5>" . "<p>" . $description . "</p>" . "\r\n";
}
}
典型结果如下 -
Array (
[0] => 39 [id] => 1
[1] => William�B.�Poff [name] => William�B.�Poff
[2] => 10 South Main Street [address1] => 10 South Main Street
[3] => Tower A, Suite 1400 [address2] => Tower A, Suite 1400
[4] => Jackson [city] => Jackson
[5] => VA [state] => VA
[6] => 24111 [zip] => 24111
[7] => downtown-jackson [neighborhood] => downtown-jackson
[8] => 5409837649 [phone] => 5401111111
[9] => http://www.foo.com [uri] => http://www.foo.com
[10] => Foo�Rogers,�PLC [firm] => Foo�Rogers,�PLC
[11] => 39
[12] => 1 [category] => Bankruptcy
[13] => 1 [level] => 1
[14] => 2009 [year] => 2009
[15] => 1
[16] => Bankruptcy
[17] => 1
[18] => Platinum [description] => Platinum )
我正在尝试基于[类别]循环,当类别等于破产时,然后输出所有破产结果,然后转到下一个类别。
这有意义吗?我从来没有对循环做过很好,所以提前感谢!
我希望的是 -
<h3>$category</h3>
<ul>
<li>$name - $description</li>
<li>$name - $description</li>
<li>$name - $description</li>
<li>$name - $description</li>
</ul>
然后迭代到下一个类别。我认为是一个嵌套循环,但我不知道如何进行嵌套循环。
答案 0 :(得分:3)
你需要一个简单的状态机。这是一种在不进行实际嵌套循环的情况下执行嵌套循环的方法。特别是因为数据流是单维的。
$category = '';
while( $result = mysql_fetch_array($query) ) {
if( $result['category'] != $category ) {
$category = $result['category'];
echo "<h3>".$category."</h3>\n";
}
echo "<h5>".$result['name']."</h5>\n";
echo "<p>".$result['description']."</p>\n";
}
如果你对每个组都有标记,这会变得更加复杂,但这是基本的想法。它依赖于同一类别中的所有内容都在一起的事实,即ORDER BY
所实现的。
P.S:不要使用extract()
;它会污染你的命名空间。
答案 1 :(得分:2)
$query = "SELECT * FROM physicians p JOIN (awards a, categories c, awardLevels l) ON (a.id = p.id AND c.id = a.category AND l.id = a.level) ORDER BY a.category, a.level ASC ";
$query = mysql_query($query);
while($row = mysql_fetch_assoc($results)) {
$categories[$row['category']][] = $row;
}
foreach($categories as $key=>$value){
echo"<h3>$key</h3>\r\n";
echo "<div><ul>\r\n";
foreach($value as $physician){
echo " <li>".$physician['name']." - ".$physician['description']."</li>\r\n";
}
echo "</ul></div>\r\n"
}