title: Codeigniter: Query for looping through two results
body: <p>I am trying to loop through two joined tables of data. One table is an image collection and another is the images. The images have a foreign key to collection.</p>
  
  <p>My question is, how do I achieve the following in my view?</p>
  
  <pre><code>foreach ($collections as $collection) {
  
      echo '&lt;ul&gt;';
  
      foreach ($collection-&gt;image as $image) {
          echo '&lt;li&gt;&lt;img src="'.$image-&gt;url.'" /&gt;&lt;/li&gt;';
      }
  
      echo '&lt;/ul&gt;';
  
  }
  </code></pre>
  
  <p>I am currently using this in the controller:</p>
  
  <pre><code>class Collection extends CI_Controller {
  
      public function index()
      {
          $this-&gt;load-&gt;model('Collection_model');
  
          $data['collections'] = $this-&gt;Collection_model-&gt;get_latest_collections();
  
          $this-&gt;load-&gt;view('collection_view.php', $data);    
  
      }
  }
  </code></pre>
  
  <p>And have the following model:</p>
  
  <pre><code>class Collection_model extends CI_Model {
  
      function get_latest_collections()
      {
          $this-&gt;db-&gt;select('*');
          $this-&gt;db-&gt;from('photo');
          $this-&gt;db-&gt;join('collection', 'photo.collection_id = collection.id');
          $this-&gt;db-&gt;order_by("collection.date_created", "DESC");
  
          $query = $this-&gt;db-&gt;get();
  
          return $query-&gt;result();
      }
  
  }
  </code></pre>
  
  <p>The problem with the above is that when I loop through the collection results I am actually looping directly through all the images. I am having to put some logic into the view to check to see if the collection id has changed to put in the . This means that I can't use next() and prev() to get the next and previous collection as the loop is looping through the images and next() and prev() gives the next and previous image rather than the next and previous collection.</p>