使用 Code Igniter 控制器和视图创建 foreach 循环

这是我遇到过几次的情况,我只想一劳永逸地解决它.

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.

我的控制器

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);

}

我的观点

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

所以基本上我试图显示一些工作表,然后在每个工作表中显示属于该工作表的剪辑.

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.

谢谢,

蒂姆

推荐答案

Code Igniter 论坛上的一位用户提出了以下解决方案.原始线程是这里.

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

单独查找每张纸的剪辑效率不高.使用 JOIN 查询同时获取两个列表.

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'
  }
} 

再次感谢,

蒂姆

相关文章