Creating foreach loops using Code Igniter controller and view(使用 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'
}
}
再次感谢,
蒂姆
这篇关于使用 Code Igniter 控制器和视图创建 foreach 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Code Igniter 控制器和视图创建 foreach 循环
基础教程推荐
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01