phparrayscodeignitergroupingresultset

How to group the results of a CodeIgniter query result set by a column


I want to display some categories and their member data like this:

Fruits

Animals

But what I got is something like this:

Fruits

Fruits

Fruits

Animals

Animals

Animals

Here is what I did. In category_model:

function getCategoryMembers(){
   $this->db->join('members','members.category_id=categories.id','left');
   return $this->db->get('categories')->result();
}

In controller, I pass the member and category data.

$data['members'] = $this->category_model->getCategoryMembers();

And, in my view, I write it like this.

<?php foreach ($members as $m) : // list the members ?>
    <?php echo $m->category_name ?>
   <?php echo $m->member_name ?>
<?php endforeach; ?>

Please tell me how to display the data like I want above. I suspect that I have to modify the database query in the model, and also how I loop it, but I'm not sure how.


Solution

  • I think you need to modify the output of the model. In the controller try this(just modify the columns):

    $rec = $this->category_model->getCategoryMembers();
    $new_rec = array();
    foreach ($rec as $k => $v) {
        $new_rec[$v->category][] = $v->member;
    }
    $data['members'] = $new_rec;
    

    And for the view :

    <?foreach ($members as $k => $v):?>
      <h3><?php echo $k ?></h3>
        <?if($v):?>
            <?foreach ($v as $m):?>
                <p><?=$m?></p>
            <?endforeach;?>
        <?endif;?>
    <?endforeach;?>