<?php
namespace app\Admin\Model;
use think\Model;
Class Menu extends Model {
/**
* @param [type] $list [列表]
*
* @param string $pk [id]
*
* @param string $pid [父级id]
*
* @param string $child [树子节点]
*
* @param integer $root [树的层级]
*
* @return list_to_tree( $data );直接转为树级数据
*/
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
// 创建Tree
$tree = array();
if (is_array($list)) {
// 创建基于主键的数组引用
$refer = array();
foreach ($list as $key => $data) {
$refer[$data[$pk]] =& $list[$key];
}
foreach ($list as $key => $data) {
// 判断是否存在parent
$parentId = $data[$pid];
if ($root == $parentId) {
$tree[] =& $list[$key];
}else{
if (isset($refer[$parentId])) {
$parent =& $refer[$parentId];
$parent[$child][] =& $list[$key];
}
}
}
}
return $tree;
}
/**
* 树转为列表选项
* @param $list [列表]
*
* @param integer $level [层级]
*
* @param string $repeat [循环输出]
*
* @return 模板中{:tree_to_menu_select($menuList)}方式调用
*/
function tree_to_menu_select($list,$level = 0,$repeat = " - - ")
{
$data = '';
foreach ($list as $key => $value) {
$data = $data."<option value='".$value['id']."'>".str_repeat($repeat, $level).$value['name']."</option>";
if (!empty($value['_child'])) {
$data = $data.tree_to_menu_select($value['_child'],$level+1);
}
}
return $data;
}
}