Welcome Guest, Not a member yet? Register   Sign In
Multiple Foreach Loops
#1

[eluser]Timothy_[/eluser]
Hello,

This is a situation I have found myself in a few times and I just want clear it up once and for all.

Best just to show you what I need to do in some example code.

My Controller

Code:
function my_controller()
{

$id = $this->uri->segment(3);

$this->db->from('cue_sheets');
$this->db->where('id', $id);
$data['get_cue_sheets'] = $this->db->get();

$this->db->from('clips');
$this->db->where('sheet_id', ' CUE SHEET ID GOES IN HERE ??? ');
$data['get_clips'] = $this->db->get();

$this->load->view('show_sheets_and_clips', $data);

}
My View

Code:
<?php if($get_cue_sheets->result_array()) { ?>
    <?php foreach($get_cue_sheets->result_array() as $sheetRow): ?>
        <h1>&lt;?php echo $sheetRow['sheet_name']; ?&gt;</h1>
        <br/>
        &lt;?php if($get_clips->result_array()) { ?&gt;
            <ul>
                &lt;?php foreach($get_clips->result_array() as $clipRow): ?&gt;
                    <li>&lt;?php echo $clipRow['clip_name']; ?&gt;</li>
                &lt;?php endforeach; ?&gt;
            </ul>
        &lt;?php } else { echo 'No Clips Found'; } ?&gt;
    &lt;?php endforeach; ?&gt;
&lt;?php } ?&gt;

So basically I am trying to display a number of sheets and then within each of those sheets the clips that belong to that sheet.

I hope this makes sense to someone out there.

Thanks,

Tim
#2

[eluser]mddd[/eluser]
It's not efficient to look up the clips for every sheet separately. Use a JOIN query to get both lists at the same time.
Code:
// get the data
$this->db->from('cue_sheets');
$this->db->where('cue_sheets.id', $id);
$this->db->join('clips', 'clips.sheet_id = cue_sheets.id', 'left');
$rawdata = $this->db->get()->result_array();
// prepare the data into a multidimensional array
$data = array();
foreach($rawdata as $row)
{
  // if this is the first clip of a new sheet, make a new entry for it
  if (!isset($data[$row['id']]))
  {
    $data[$row['id']] = $row;
    $data[$row['id']]['clips'] = array();
  }  

  // add the current clip to the sheet
  $data[$row['id']]['clips'][] = $row;
}

Now in your view you can loop through the sheets, and within that, loop through the clips:
Code:
foreach($data as $sheet) {
  // make header etc.
  if (sizeof($sheet['clips']))
  {
    foreach($sheet['clips'] as $clip)
    {
      // show clip
    }
  } else {
    // show 'no clips'
  }
}




Theme © iAndrew 2016 - Forum software by © MyBB