标签:
yii2 无限级分类 模型层 <?php namespace frontend\models; use Yii; /** * This is the model class for table "region". * * @property integer $region_id * @property integer $parent_id * @property string $region_name * @property integer $region_type */ class Region extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return ‘region‘; } /** * @inheritdoc */ public function rules() { return [ [[‘parent_id‘, ‘region_type‘], ‘integer‘], [[‘region_name‘], ‘string‘, ‘max‘ => 120] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ ‘region_id‘ => ‘Region ID‘, ‘parent_id‘ => ‘Parent ID‘, ‘region_name‘ => ‘Region Name‘, ‘region_type‘ => ‘Region Type‘, ]; } /** * 地区分类 */ public function getinfo() { $connection = \Yii::$app->db; $region=$connection->createCommand(‘SELECT * FROM region where region_type != 0‘)->queryAll(); return $this->left($region,$parent_id=1); } public function left($region,$parent_id) { $child=array(); foreach($region as $key=>$v) { if($v[‘parent_id‘]==$parent_id) { $child[]=$v; } } if(empty($child)) { return null; } foreach($child as $key=>$s) { $kk_id=$this->left($region,$s[‘region_id‘]); if($kk_id){ $child[$key][‘child‘]=$kk_id; } } return $child; } } 控制器 $region = new Region(); $ros = $region->getinfo(); //print_r($ros);die; return $this->renderPartial(‘companylist‘,[‘region‘=>$ros]); 视图层 <? foreach($region as $key=>$reg) { ?> <dl> <dt><?= $reg[‘region_name‘] ?></dt> <dd> <? foreach($reg[‘child‘] as $k=>$r) { ?> <span><?= $r[‘region_name‘] ?></span> <? } ?> </dd> </dl> <? } ?>
标签:
原文地址:http://www.cnblogs.com/jhy-ocean/p/5364870.html