Yii无限级分类实现下拉列表效果

最近在项目中用到无限级,就研究了一下。其实无限级分类的原理很简单,主要就运用递归函数,进行取值。下面我就简单写了一下关于用递归函数,实现无限级分类下拉列表效果。

首先,创建你数据表,结构如下:

1
2
3
4
5
6
CREATE TABLE channel(
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
pid INT(11) UNSIGNED NOT NULL,
`name` VARCHAR(20),
PRIMARY KEY(id)
)ENGINE=INNODB DEFAULT CHARSET = utf8;

其中,pid为栏目的父级ID,若pid为0表示为顶级栏目。
Model中的代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//将Yii CDbCriteria 查询出来的结果对象转换成数组
public function converToArray($obj){
$result = array();
if (is_object($obj)) {
$result[] = $obj->attributes;
}else{
foreach ($obj as $value) {
$result[] = $value->attributes;
}
}
return $result;
}

//实现下拉列表的递归函数
public function getChannelList($pid,$prefix = ”){
$res = ”;
$criteria = new CDbCriteria;
$criteria->select = ‘*';
$criteria->condition = ‘pid=:pid';
$criteria->params = array(‘:pid’ => $pid);
$result = $this->findAll($criteria);
$result = $this->converToArray($result);

if(!$result) return ”;

foreach ($result as $key => $value) {
if($value[‘pid’] == $pid){
$res .= “<option value=”.$value[‘id’].”>”.$prefix.$value[‘name’].”</option>\n”;
}
$res .= $this->getChannelList($value[‘id’],$prefix.’–‘);
}
return $res;
}

Controller代码:

1
2
3
4
5
6
7
8
9
10
11
class IndexController extends Controller{
public function actionIndex(){
header(‘Content-type:text/html;charset=utf-8′);
$ChannelModel = new ChannelModel;
$channelInfo = $ChannelModel->getChannelList(0);

$this->renderpartial(‘index’,array(
‘channel’=>$channelInfo
));
}
}

View代码:

1
2
3
4
5
6
7
<div>
<form action=”” method=”post”>
<select name=”ChannelModel[id]” id=”ChannelModel_id”>
<?php echo $channel;?>
</select>
</form>
</div>