简体   繁体   English

列表中的单独主题标题

[英]Separate subject headings in list

<?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>

This produces a list of all entries in the database. 这将生成数据库中所有条目的列表。 However I want to separate out the "subject" data as a heading above each title within that subject group. 但是,我想将“主题”数据作为该主题组中每个标题上方的标题分开。 Eg: 例如:

SUBJECT 1 主题1

Title 1 标题1

Title 2 标题2

Title 3 标题3

SUBJECT 2 主题2

Title 1 标题1

Title 2 标题2

etc 等等

How should I modify the above code to achieve this? 我应该如何修改上面的代码来实现这一目标? I'm guessing it will need a nested loop, but not sure how to put this together. 我猜想它将需要一个嵌套循环,但是不确定如何将其组合在一起。

You can add the subjects into an array in one loop and then in for each subject in that array you can go through the whole list and echo the title and author if the subject matches. 您可以将主题一次性添加到一个数组中,然后可以对该数组中的每个主题进行遍历,并在主题匹配时回显标题和作者。

$subjects = array();
array_push($subjects, $r['subject']);

usage requested so something like this though if someone could edit it to be correct and more efficient... 用法要求如此,但如果有人可以对其进行编辑以使其更正确,更有效,则类似这样...

  <?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";}
  }
  ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM