码迷,mamicode.com
首页 > 其他好文 > 详细

无限级分类

时间:2016-04-07 20:17:13      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!