Creating foreach loops using Code Igniter controller and view

前端 未结 4 1747
一整个雨季
一整个雨季 2021-01-17 02:35

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.

4条回答
  •  Happy的楠姐
    2021-01-17 02:52

    A user on the Code Igniter Forums came up with the solution below. The original thread is here.

    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.

    // 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:

    foreach($data as $sheet) {
      // make header etc.
      if (sizeof($sheet['clips']))
      {
        foreach($sheet['clips'] as $clip)
        {
          // show clip
        }
      } else {
        // show 'no clips'
      }
    } 
    

    Thanks again,

    Tim

提交回复
热议问题