简体   繁体   中英

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

Title 1

Title 2

Title 3

SUBJECT 2

Title 1

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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