I'm relatively new to PHP and still learning, and I recognize that this is a rookie question, but I'd love and appreciate any help that you can provide.
I'm currently working on coding a website that uses PHP and MySQL to pull and organize data from both a "courses" and "categories" database table. Each row in the "courses" table is associated with a particular course category through the column "category_id," which is linked to the relevant "id" column in the "categories" table.
So, for example, if category 3 in the "categories" table is "Music" and a particular course is on music, that course's "category_id" column value will be set to "3" in the "courses" table. (I hope that I explained all of that appropriately; my apologies if it's unclear).
I'd like to display all of the course category names that currently contain courses, and also display all of the course names within each of those categories underneath each category name. So, for example:
- Music: (1) Rock, (2) Jazz
- Painting: (1) Watercolor, (2) Acrylic
Here is the code that I'm using to do this. I'm using an MVC framework in which I've passed all of the data from both the "courses" and "categories" tables into this view as the associative arrays $categories and $courses.
<?php foreach ($categories as $category) : ?>
<h4><?php echo ($category['name']); ?></h4>
<?php foreach ($courses as $course) {
if ($course['category_id'] == $category['id']) : ?>
<p><?php echo ($course['name']); ?></p>
<?php endif;
}
endforeach; ?>
The problem that I'm running into is that I have category rows in my "categories" table for which I don't currently yet have any corresponding courses in the "courses" table. As I build out the website, this will change, but for now and for organization sake I don't want to delete those rows from the "categories" table.
So now, given the above code, I'm outputting a list of categories and courses that looks like this:
- Dance:
- Sculpture:
- Music: (1) Rock, (2) Jazz
- Painting: (1) Watercolor, (2) Acrylic
So finally, my question: how would I go about looping through each of the categories, and only displaying the category name if there are corresponding courses associated with that category_id in the "courses" table? (In reference to the example above, to skip over and not display the "Dance" and "Sculpture" categories because there aren't yet any courses associated with those categories).
Again, my apologies if anything above is unclear, and I very much appreciate anyone's help!
Best, Josh