Tim*_*Tim 0 php model-view-controller foreach controller codeigniter
这是我几次发现自己的情况,我只想一劳永逸地清理它.
最好只是为了向您展示我在一些示例代码中需要做的事情.
我的控制器
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);
}
Run Code Online (Sandbox Code Playgroud)
我的看法
<?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 } ?>
Run Code Online (Sandbox Code Playgroud)
所以基本上我试图显示一些工作表,然后在每个工作表中显示属于该工作表的剪辑.
我希望这对那里的人有意义.
谢谢,
蒂姆
Code Igniter论坛上的用户提出了以下解决方案.原始帖子就在这里.
单独查找每个工作表的剪辑效率不高.使用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;
}
Run Code Online (Sandbox Code Playgroud)
现在在您的视图中,您可以遍历工作表,并在其中循环浏览剪辑:
foreach($data as $sheet) {
// make header etc.
if (sizeof($sheet['clips']))
{
foreach($sheet['clips'] as $clip)
{
// show clip
}
} else {
// show 'no clips'
}
}
Run Code Online (Sandbox Code Playgroud)
再次感谢,
蒂姆