|
本帖最后由 xloong 于 2013-7-6 19:20 编辑
被这个问题困扰了好几天,主要是被刚开始的思路限制住了,今天终于搞定了,当然,搞定出的代码也很。。。。感觉效率不高,贴出来一方面给后来人一个思路,一方面也请高手看看,提供下更好的建议
数据库(简略的写下,大家能理解就行了):
article:
aid
cid
title ...
category:
cid
cname
模型 article_m
PHP复制代码 function article_select_limit ($start,$end)
{
$this->db->limit($end,$start);
$this->db->join('category','article.cid=category.cid');
$query=$this->db->get('article');
return $query->result();
} 复制代码
模型 category_m
PHP复制代码 function category_select_all()
{
$this->db->order_by('oid asc, cid asc');
$query=$this->db->get('category');
return $query->result();
} 复制代码
控制器:
PHP复制代码 $this->load->model('Category_m');
$data['category'] = $this->Category_m->category_select_all();
$this->load->model('Article_m');
foreach ($data['category'] as $row) {
$data['article'][$row->cid]['cid']=$row->cid;
$data['article'][$row->cid]['cname']=$row->cname;
$data['article'][$row->cid]['arti']=$this->Article_m->article_select_cid_limit($row->cid,0,5) ;
} 复制代码
var_dump('article') 的结果(数据库里2个分类,4篇文章,每个分类2个文章):
HTML复制代码 array (size=2)
1 =>
array (size=3)
'cid' => string '1' (length=1)
'cname' => string '目录1' (length=7)
'arti' =>
array (size=2)
0 =>
object(stdClass)[22]
...
1 =>
object(stdClass)[23]
...
2 =>
array (size=3)
'cid' => string '2' (length=1)
'cname' => string '测试2' (length=7)
'arti' =>
array (size=2)
0 =>
object(stdClass)[24]
...
1 =>
object(stdClass)[25]
... 复制代码
视图:
PHP复制代码 foreach($article as $row):
echo '<b>'.anchor ('home/category/'.$row['cid'], $row['cname'], array('title' => $row['cname'])).'</b>';
foreach($row['arti'] as $arti):
echo '<h3>'.anchor ('home/article/'.$arti->aid, $arti->title,array('title' => $arti->title)).'</h3>'; ?>
endforeach;
echo '<hr>';
endforeach; 复制代码
|
|