dongpouda6700 2010-06-14 23:21 采纳率: 100%
浏览 44
已采纳

使用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.

My Controller

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

<?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.

Thanks,

Tim

  • 写回答

4条回答 默认 最新

  • dpmfur2635 2010-06-16 00:47
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?