Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

* foreach inside foreach codeigniter 2?

In codeigniter 2.1 I'm trying to display channels by category. So if i have a category called Film, i should see a list of Channels within Film. I tried a nested foreach loop to accomplish this but can't seem to get it to work.

My tables structure is something like this but more complicated:

Database structure

  • My model:

    <?php
    
    class Pages_model extends CI_Model {
    
    
    function get_channels_by_categ_tv()
    {
    
      $this->db->select('categories.category_name, channels.channel_name');
      $this->db->from('type_categ');
      $this->db->join('categories', 'categories.category_id = type_categ.category_id');
      $this->db->join('channels', 'channels.channel_id = type_categ.channel_id');
      $this->db->order_by('categories.category_id');
    //$this->db->group_by(array('categories.category_id')); 
      $query = $this->db->get();
    
      if($query->num_rows() == 0)
      {
        #no channels
        return false;
      }
    
      return $query->result_array();
    }
    
    }
    
  • in the view:

              <ul class="slides">
                <li>
                    <?php foreach ($category_chaneels as $category): ?>
                    <div class="programe-tv_link">
                        <p><?=$category['category_name'];?></p>
                           <dd> <a href=""> >> <?=$category['channel_name'];?></a></dd>
                    </div>
                    <?php endforeach; ?>                  
                </li>
              </ul>
    
  • controller (Pages):

    public function index()
    {
    
    $data['category_chaneels'] = $this->pages_model->get_channels_by_categ_tv();
    
    $this->template->page_view($data);
    }
    

I atached image 1 and image 2, i need result like image 2 not 1.

PS. One channel can have many categories.

enter image description here Can you help me ? THX

like image 886
Alexandru Florea Avatar asked Feb 18 '26 08:02

Alexandru Florea


1 Answers

In your view, try

<?php $cat_shown = ''; ?>
<div class="programe-tv_link">
    <?php foreach ($category_chaneels as $category): ?>    
        <?php
        if ($cat_shown != $category['category_name']) {
            echo '<p>' . $category['category_name'] . '</p>';
            $cat_shown = $category['category_name'];
        }
        ?>
        <dd><a href=""> >> <?=$category['channel_name'];?></a></dd>
    <?php endforeach; ?>
</div>
like image 189
stealthyninja Avatar answered Feb 20 '26 00:02

stealthyninja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!