以下两个函数是自己在接触PHP的时候学到的,这里做一下记录只是为了怀念那个时候对于行业的那种陌生感和探索欲望,这两个函数虽然不是很难,但是用的地方不少,比如获取目录树,可以用在对类目的管理、评论等无限级的地方都可以用,话不多说,请看代码。
获取目录树 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 public function getMenu ($map ) { $menu = new model_op_menu () ; $order = "ORDER BY level ASC,sort DESC" ; $menu_list = $menu -> select ($map , '' , '' , $order , '' , '' ); $mod_list = $menu_list -> items; if (!$mod_list || empty ( $mod_list )) { return false ; } $tmp = array () ; $address = array () ; foreach ($mod_list as $k => $v ) { $id = $v [ 'id' ]; if ($v ['level' ] <= 1 ) { $tmp [$id ] = $v ; $address [$id ] = & $tmp [$id ]; } else { $pid = $v [ 'pid' ]; if (!$address [ $pid ]['child' ]) { $address [ $pid ]['child' ] = array () ; } $address [$pid ][ 'child' ][$id ] = $v ; $address [$id ] = & $address [$pid ]['child' ][ $id ]; } } return $tmp ; }
批量排序 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 public function pagesort ( ) { try { $sort = lib_BaseUtils ::getStr ( $_GET ['sort' ]); if (empty ( $sort )) { throw new Exception ( '请选择需要排序的数据!' , 0 ) ; } foreach ( $sort as $k => $v ) { if (!is_numeric ( $k ) || !is_numeric ($v )) { continue ; } $sql_bat_sort .= " WHEN { $k } THEN {$v} " ; $sql_ids .= ',' . $k ; } $menu = new model_op_menu () ; $sql = "UPDATE op_menu SET sort= CASE id " . $sql_bat_sort . " END WHERE id IN (" . trim ($sql_ids , ', ' ) . ")" ; $menu ->query ( $sql ); throw new Exception ('批量排序成功!' , 1 ); } catch (Exception $e ) { return $this ->printmsg ( $e ->getMessage (), $e ->getCode ()) ; } }
巧办法 上诉的获取目录树也可以用通过更加简单的办法来实现,在数据库设计合理的情况下,可以使用递归的方式来做。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public function getTree ($pid =0 ,&$result =[],$space =0 ) { $space +=2 ; $parents = Category ::where ('cate_pid' ,$pid )->orderBy ('cate_order' ,'DESC' )->get (); foreach ($parents as $key => $val ){ if ($val ->cate_pid != 0 ){ $val ['cate_name' ] = str_repeat (' ' ,$space ).'▲ ' .$val ['cate_name' ]; } $result [] = $val ; $this ->getTree ($val ->cate_id,$result ,$space ); } return $result ; }