sql:
CREATE TABLE `category` (
`id` int(50) NOT NULL,
`name` varchar(50) COLLATE utf8_vietnamese_ci NOT NULL COMMENT '分类名称',
`pid` int(11) NOT NULL DEFAULT '0' COMMENT '父级分类id',
`url` varchar(50) COLLATE utf8_vietnamese_ci NOT NULL COMMENT '访问地址',
`status` int(2) NOT NULL DEFAULT '1' COMMENT '状态',
`created_at` int(12) NOT NULL COMMENT '创建时间',
`updated_at` int(12) NOT NULL COMMENT '修改时间'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_vietnamese_ci;
--
-- 转存表中的数据 `category`
--
INSERT INTO `category` (`id`, `name`, `pid`, `url`, `status`, `created_at`, `updated_at`) VALUES
(1, 'cyg', 0, 'www.baidu.com', 1, 1645603515, 1645603515),
(2, 'liwen', 1, 'www.bauc.om', 1, 1645604857, 1645604857);
helpers
<?php
namespace backend\helpers;
class Tree
{
public static function getTree($list,$pid=0)
{
$tree=[];
foreach($list as $row)
{
if($row['pid']==$pid)
{
$tree[$row['id']]=$row;
$children=self::getTree($list,$row['id']);
$children&&$tree[$row['id']]['children']=$children;
}
}
return $tree;
}
public static function getTrees($list,$pid=0,$level=0)
{
static $tree=[];
foreach ($list as $k => $row) {
if($row['pid']==$pid)
{
$row['name']=html_entity_decode(str_repeat(" ",$level))."|--".$row['name'];
$tree[$row['id']]=$row;
unset($list[$k]);
self::getTrees($list,$row['id'],$level+1);
}
}
return $tree;
}
}
后台数据:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model backend\models\Category */
/* @var $form yii\widgets\ActiveForm */
$list=\backend\models\Category::find()->asArray()->all();
$tree=\backend\helpers\Tree::getTrees($list);
$tree=\yii\helpers\ArrayHelper::map($tree,'id','name');
array_unshift($tree,Yii::t('backend','parent'));
?>
<div class="category-form">
<?php $form =ActiveForm::begin(); ?>
<?= $form->field($model, 'id')->textInput() ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pid')->dropDownList($tree) ?>
<?= $form->field($model, 'url')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'status')->radioList(\backend\models\Category::getStatusArray()) ?>
<?= $form->field($model, 'created_at')->textInput() ?>
<?= $form->field($model, 'updated_at')->textInput() ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
前台视图:
<ul class="nav">
<?php $list=\backend\models\Category::find()->asArray()->all();
$categorys=\backend\helpers\Tree::getTree($list);
?>
<?php foreach($categorys as $category):?>
<li><a href="about.html"><?= $category['name']?></a>
<?php foreach($category['children'] as $aa):?>
<ul class="two">
<li><a href="about.html"><?= $aa['name']?></a></li>
</ul>
<?php endforeach;?>
</li>
<?php endforeach;?>
</ul>
最终效果: