<?php require_once('Connections/pdoConnect.php'); ?>
<?php
// Issue the query
$pdo_recordset1 = $conn->query("SELECT id, title, author, subject FROM audio");
$pdo_recordset1->setFetchMode(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Audio List</title>
</head>
<body>
<?php
// Now iterate over every row and display it
$n = 0;
while($r = $pdo_recordset1->fetch(PDO::FETCH_ASSOC))
{
?>
<a href="PDO_detail.php?item=<?php echo $r['id']?>">
<?php echo ($r['subject'])?><?php echo ($r['title'])?><?php echo ($r['author'])?></a><br />
<?php
++$n;
}
if(0 == $n)
{
echo "Sorry there are no items to display";
}
?>
</body>
</html>
这将生成数据库中所有条目的列表。但是,我想将“主题”数据作为该主题组中每个标题上方的标题分开。例如:
主题1
标题1
标题2
标题3
主题2
标题1
标题2
等
我应该如何修改上面的代码来实现这个目标?我猜它需要一个嵌套循环,但不知道如何把它放在一起。
答案 0 :(得分:1)
您可以在一个循环中将主题添加到array,然后对于该数组中的每个主题,您可以浏览整个列表,并在主题匹配时回显标题和作者。
$subjects = array();
array_push($subjects, $r['subject']);
<?php
$subjects = array();$n=0;
while($r = $pdo_recordset1->fetch(PDO::FETCH_ASSOC))
{array_push($subjects, $r['subject']);}
while($s = $subject->$subjects)
{
while($r = $pdo_recordset1->fetch(PDO::FETCH_ASSOC))
{
if($r['subject']==$s)
{
?><a href="PDO_detail.php?item=<?php echo $r['id']?>">
<?php echo ($r['subject']); echo ($r['title']); echo ($r['author'])?>
</a><br /><?php
}
++$n;
}
if(0 == $n){echo "Sorry there are no items to display";}
}
?>