Skip to main content

菜单无限分类的两种常见案例

写个系统就会遇到这个问题,这次又遇到,于是我记录下来,再写的时候,我就依葫芦画瓢。

总结:

  1. 第一种是数组循环嵌套
  2. 第二种是select下的选项,要显示出层级关系。

数据库字段

protected $fillable = ['id','parent_id','order','title','icon','uri','permission','created_at','updated_at'];

第一种是数组循环嵌套

    //菜单
public static function getMenuPage($id = 0)
{
$frist_list = self::where(['parent_id'=>$id])->orderBy('order','ASC')->get()->toArray();
if (empty($frist_list))
{
return $frist_list;
}else{
foreach ($frist_list as &$row)
{
$child = self::where(['parent_id'=>$row['id']])->orderBy('order','ASC')->get()->toArray();
$row['child_data'] = empty($child) ? [] : self::getMenuPage($row['id']);
}
return $frist_list;
}
}

第二种是select下的选项,要显示出层级关系。

    //下拉菜单
public static function createSortOptions ($selected=0,$parent_id=0,$n=0)
{
$options = '';
if ($parent_id == 0)
{
$options .= '<option value="0">请选择</option>';
}
$list = self::where('parent_id',$parent_id)->orderBy('order','asc')->get();
if ($list)
{
$n++;
foreach ( $list as $row)
{
$options .="<option value='{$row['id']}'";
if ($row['id'] == $selected)
{
$options .=' selected ';
}
$options .=">".str_repeat('&nbsp;',4*$n).'|--'.$row['title']."</option>";
$options .= self::createSortOptions ($selected,$row['id'],$n);
}
}
return $options;
}