I have two tables called categories and topics.
categories has columns category_id and category_title. topics has columns topic_id, topic_title, and category_id.
I currently display the columns like so:
$result = mysqli_query($db_server, 'SELECT c.category_title, t.topic_title FROM categories c JOIN topics t on c.category_id = t.category_id');
while ($row = mysqli_fetch_array($result))
{
$category_title[] = $row['category_title'];
$topic_title[] = $row['topic_title'];
}
<?php
foreach ($category_title as $category_title):
echo htmlspecialchars($category_title, ENT_QUOTES, 'UTF-8');?><br />
<?php endforeach; ?>
<?php
foreach ($topic_title as $topic_title):
echo htmlspecialchars($topic_title, ENT_QUOTES, 'UTF-8');?><br />
<?php endforeach; ?>
This will display as:
Category 1
Category 1
Category 2
Topic 1
Topic 2
Topic 3
Topic 1 and 2 are assigned to Category 1, while Topic 3 is assign to Category 2.
How can I have Category display once if there are multiple topics assign to it, such as:
Category 1
Category 2
Topic 1
Topic 2
Topic 3
Please no classes and objects examples. I’m not learning that yet.
You can run query two time first for category then run new query to selected topic according to category as below: