从CodeIgniter中的两个表中检索数据 [英] Retrieving data from two tables in CodeIgniter
问题描述
我想显示一些类别及其成员数据,如下所示:
I want to display some categories and their member data like this:
水果
- 橙色
- 葡萄
- 苹果
动物
- 猫
- 狗
- 马
但是我得到的是这样的东西:
But what I got is something like this:
水果
- 橙色
水果
- 葡萄
水果
- Apple
动物
- 猫
动物
- 狗
动物
- 马
这就是我所做的。在category_model中:
Here is what I did. In category_model:
function getCategoryMembers(){
$this->db->join('members','members.category_id=categories.id','left');
return $this->db->get('categories')->result();
}
在控制器中,我传递成员和类别数据。
In controller, I pass the member and category data.
$data['members'] = $this->category_model->getCategoryMembers();
在我看来,我是这样写的。
And, in my view, I write it like this.
<?php foreach ($members as $m) : // list the members ?>
<?php echo $m->category_name ?>
<?php echo $m->member_name ?>
<?php endforeach; ?>
请告诉我如何在上方显示数据。我怀疑我必须修改模型中的数据库查询,以及如何循环查询,但是我不确定如何修改。谢谢您的帮助。
Please tell me how to display the data like I want above. I suspect that I have to modify the database query in the model, and also how I loop it, but I'm not sure how. Thanks for your help.
推荐答案
我认为您需要修改模型的输出。
在控制器中尝试执行此操作(只需修改列):
I think you need to modify the output of the model. In the controller try this(just modify the columns):
$rec = $this->category_model->getCategoryMembers();
$new_rec = array();
foreach ($rec as $k => $v) {
$new_rec[$v->category][] = $v->member;
}
$data['members'] = $new_rec;
对于视图:
<?foreach ($members as $k => $v):?>
<h3><?php echo $k ?></h3>
<?if($v):?>
<?foreach ($v as $m):?>
<p><?=$m?></p>
<?endforeach;?>
<?endif;?>
<?endforeach;?>
这篇关于从CodeIgniter中的两个表中检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!