我被困在我的PHP(CI + Bootstrap)家庭作业代码中,我将解释它的(简化)细节:
这是我的MVC代码:
型号
function get_data($table)
{
return $this->db->get($table);
}
控制器
public function faculty_profile($id)
{
$where = array('faculty_id' => $id);
$data['faculty'] = $this->db->query("select * from faculty f, students s where f.faculty_id=s.faculty_id and f.faculty_id='$id'")->result();
$this->load->view('faculty_profile', $data);
}
查看(简体)
<?php foreach($faculty as $f) { ?>
<tr>
<td><?php echo $f->faculty_name?></td>
</tr>
<tr>
<td><?php echo $f->head_of_faculty?></td>
</tr>
<tr>
<td>
<b>Students enrolled in this faculty</b>
<?php echo $f->students_name?>
</td>
</tr>
<?php } ?>
(简化的)结果如下(我在同一系中登记了两行):
------
Information Technology //faculty_name
Mr. Henry //head_of_faculty
Students enrolled in this faculty
Adam
------
------
Information Technology //faculty_name
Mr. Henry //head_of_faculty
Students enrolled in this faculty
Brian
------
下面就是我想要的样子:
------
Information Technology //faculty_name
Mr. Henry //head_of_faculty
Students enrolled in this faculty
Adam
Brian
------
问题是,我必须在哪里修补才能获得想要的结果?
哦,我已经试过像这样放置2个foreach:
<?php foreach($faculty as $f) { ?>
<tr>
<td><?php echo $f->faculty_name?></td>
</tr>
<tr>
<td><?php echo $f->head_of_faculty?></td>
</tr>
<?php foreach($faculty as $f) { ?>
<tr>
<td>
<b>Students enrolled in this faculty</b>
<?php echo $f->students_name?>
</td>
</tr>
<?php } ?>
<?php } ?>
结果如下:
------
Information Technology //faculty_name
Mr. Henry //head_of_faculty
Students enrolled in this faculty
Adam
Brian
------
------
Information Technology //faculty_name
Mr. Henry //head_of_faculty
Students enrolled in this faculty
Adam
Brian
------
在此先感谢您的帮助,
答案 0 :(得分:0)
您提到视图“ faculty_profile”仅显示该学院的在校学生。这意味着它将只显示1个教员。因此,您无需循环$ faculty。如下更改您的控制器代码。
$data['faculty'] = $this->db->query("select * from faculty f where f.faculty_id='$id'")->result();
$data['faculty']['students'] = $this->db->query("select * from students s where s.faculty_id='$id'")->result();
$this->load->view('faculty_profile', $data);
如下更改视图
<tr>
<td><?php echo $faculty->faculty_name?></td>
</tr>
<tr>
<td><?php echo $faculty->head_of_faculty?></td>
</tr>
<tr><td>Students enrolled in this faculty</td></tr>
<?php foreach($faculty['students'] as $student ) { ?>
<tr>
<td>
<?php echo $student->students_name?>
</td>
</tr>
<?php } ?>