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

时间:2010-06-14 23:21:54

标签: php model-view-controller codeigniter controller foreach

这是我几次发现自己的情况,我只想一劳永逸地清理它。

最好只是为了向您展示我在一些示例代码中需要做的事情。

我的控制器

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

所以基本上我试图显示多张纸张,然后在每张纸张中显示属于该纸张的剪辑。

我希望这对那里的人有意义。

谢谢,

4 个答案:

答案 0 :(得分:6)

Code Igniter论坛上的用户提出了以下解决方案。原始帖子是here

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

// 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;
}

现在,在您的视图中,您可以遍历工作表,并在其中循环浏览剪辑:

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

再次感谢,

答案 1 :(得分:1)

您应该在两个表的模型中进行连接,并创建一个结果,稍后您将通过控制器移动到视图中。

请记住不要在控制器中放置查询。

也许是这样的事情:

function get_data($cue_sheets){
$this->db->select(clips.*);
$this->db->from('clips');
$this->db->join('cue_sheets', 'clips.idcuesheet = cue_sheets.idcuesheet' );
$this->db->where('cue_sheets.idcuesheet', $cue_sheets);
$query = $this->db->get();
}

或类似的东西。

然后将它带到控制器

$data['clips'] = $this->clips->get_data($cue_sheets);

最后到你的观点

foreach($clips as $clip){
echo $clip->clip_name;
}

希望有所帮助

答案 2 :(得分:0)

据我所知,实际上没有办法从视图中将数据传回控制器。我自己也没有觉得有必要。您的控制器应该收集数据,然后将其传递给视图。如果您有从数据库结果中获取的其他数据,请先执行此操作,然后将其与原始数据一起传递到视图中。

虽然我可能不理解你的问题......

答案 3 :(得分:0)

我不完全确定我理解你,但我想你想要从第一个db调用给出的所有“工作表”中获取所有“剪辑”。也许以下可能有效:

$this->db->from('clips');
$this->db->where_in('sheet_id', array_map( function($sheet) { return $sheet['id'] }, $data['get_cue_sheets']->result_array() ) );
$data['get_clips'] = $this->db->get();
相关问题