php分类目录下拉列表(递归+无限分类)

1.在catalog类里面:

	/**
	 * 级联显示
	 * 分类目录递归列表
	 * 返回父类的所有子类
	 * &$categoryList 引用传值返回
	 */
const SHOW_SELECT='————请选择————';

public function showAllCategory(&$categoryList,$category,$parentid=0,$separate="") { foreach($category as $k=>$v){ if($v['parentid']==$parentid){ $v['title']=$separate.$v['title']; $categoryList[]=$v; $this->showAllCategory($categoryList,$category,$v['id'],$separate."——"); } } } /** * 分类目录下拉列表 */ public function showAllSelectCategory($module,$selectText='') { $category=Category::model()->select('id,title,parentid')->order('sort desc')->findAll("module=$module"); $categoryList=array(); $this->showAllCategory($categoryList,$category); if(!empty($selectText)) $categorys=array('0'=>$selectText); else $categorys=array(''=>Category::SHOW_SELECT); foreach($categoryList as $v){ $categorys[$v[id]]=$v[title]; } return $categorys; }

  2.控制器映射:

		$this->render('create',array(
			'model'=>$model,
			'categorys'=>Category::model()->showAllSelectCategory(Yii::app()->params['module']['article']),
		));

 3.视图:

	<div class="row">
		<?php echo $form->labelEx($model,'cid'); ?>
		<?php echo $form->dropDownList($model,'cid',$categorys); ?>
	</div>

  

 扩展INDEX页面的下拉搜索功能:

控制器代码:

    	if(!empty($_GET['cid'])){
    		$categoryList=array();
    		$categoryList[]=$_GET['cid'];
			Category::model()->getAllCategoryIds($categoryList,Category::model()->findAll('module='.Yii::app()->params['module']['article']),$_GET['cid']);
		    $criteria->addInCondition('cid',$categoryList);
    	}
    	if(!empty($_GET['title']))
    		$criteria->addSearchCondition('title',$_GET['title']);
		$dataProvider=new CActiveDataProvider('Article',array(
			'criteria'=>$criteria,
			'pagination'=>array(
        		'pageSize'=>Yii::app()->params['girdpagesize'],
    		),	
		));

  类里面递归把符合条件的之类也查找出来:

public function getAllCategoryIds(&$categoryList,$category,$parentid=0){
			foreach($category as $k=>$v){
			if($v['parentid']==$parentid){
				$categoryList[]=$v['id'];
				$this->getAllCategoryIds($categoryList,$category,$v['id']);
			}
		}
	}

  

原文地址:https://www.cnblogs.com/fengzhiqiangcaisangzi/p/3382609.html