I have two databases tables called article_category and article_case. They are supposed to be combined in a webpage as below:
Article category[title] Article category[description] Article case[title] Article case[contents] Article case[title] Article case[contents]
This should repeat itself using foreach until all article categories are populated on the page.
Each article_case will also use foreach, but it has to respect its ‘category_id’ value which matches the ‘id’ in article_category .
I’m having trouble filtering the article_case table so that it only picks up rows from its parent ‘category_id’.
This is my current php code (which only makes an array of each table):
$this->db->select( "id,title,description" );
$this->db->from( 'article_category' );
$query_article_category = $this->db->get_compiled_select();
$query = $this->db->query( $query_sustainability_category . 'ORDER BY sort ASC ' );
foreach ($query->result_array() as $val) {
$data['article_category_posts'][$val['id']] = $val;}
$this->db->select( "id,category_id,title,contents" );
$this->db->from( 'article_case' );
$query_article_case = $this->db->get_compiled_select();
$query = $this->db->query( $query_article_case);
$data[ 'article_cases' ] = $query->result_array();
And here is my html:
<?php foreach ($article_category_posts as $key => $val) { ?>
<section>
<h2><?php echo $val['title']; ?></h2>
<p><?php echo $val['description']; ?></p>
</section>
<?php foreach ($article_cases as $key => $val) { ?>
<section>
<h3><?php echo $val['title']; ?></h3>
<p><?php echo $val['contents']; ?></p>
</section>
<?php } ?>
<?php } ?>
The current setup will input all article_cases disregarding the category_id.
How can I use foreach while assigning each article_case to their respective article_cateogry?
2
Answers
This would generate unnecessary amount of queries to the DB server.
The rly basic approach would be:
SELECT * FORM a_category
SELECT * FROM a_case WHERE category_id = {$category['id']}
The second one is to combine the categories and cases right in the query with join and adjust the resulting data in php:
You can use a query to get all the records of
article_case
with relatedarticle_category
.group the query result by
category_id
.array group by function
in view you can show as below