Skip to content

Commit 7016970

Browse files
committed
菜单列表返回树形结构
1 parent 374b44b commit 7016970

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

components/Helper.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,4 +274,35 @@ public static function get_shops()
274274

275275
return $shop_id;
276276
}
277+
278+
/**
279+
* 树形格式化数据
280+
*
281+
* @param array $list 数据
282+
* @param string $pk 主
283+
* @param string $pid 父
284+
* @param string $child 子集变量名
285+
* @param int $root 根节点
286+
*
287+
* @return array
288+
*/
289+
public static function makeTree($list, $pk = 'id', $pid = 'pid', $child = 'child', $root = 0)
290+
{
291+
$tree = array();
292+
$packData = array();
293+
foreach ($list as $data) {
294+
$packData[$data[$pk]] = $data;
295+
}
296+
foreach ($packData as $key => $val) {
297+
if ($val[$pid] == $root) {
298+
//代表根节点
299+
$tree[] =& $packData[$key];
300+
} else {
301+
//找到其父类
302+
$packData[$val[$pid]][$child][] =& $packData[$key];
303+
}
304+
}
305+
306+
return $tree;
307+
}
277308
}

controllers/MenuController.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,11 @@ public function actionUserMenu()
5757
public function actionIndex()
5858
{
5959
$res = $this->menu_model->getMenuSource();
60-
60+
$is_tree = Yii::$app->request->get('is_tree');
61+
if ($is_tree) {
62+
return Helper::makeTree($res, 'name', 'parent_name', 'child', null);
63+
}
64+
6165
return $res;
6266
}
6367

0 commit comments

Comments
 (0)