当前位置: 首页 > 编程日记 > 正文

PHP 实现无限分类

最近打算做一个blog,通常每篇文章都有属于自己的分类。下面就记录下我在写blog时实现无限分类的过程。php框架用的是laravel,根据注释也能轻松改成你习惯的框架。

数据表设计

CREATE TABLE `article_category` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT,`pid` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '父id',`name` char(50) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '分类名',`statu` enum('y','n') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'y' COMMENT '是否显示',`created_at` timestamp NULL DEFAULT NULL,`updated_at` timestamp NULL DEFAULT NULL,`remark` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',PRIMARY KEY (`id`),KEY `article_category_pid_index` (`pid`)
) ENGINE=MyISAM AUTO_INCREMENT=18 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

程序设计

添加分类

public function addClassify(Request $request)
{// laravel 框架自带的验证机制$this->validate($request,['name' => 'required|unique:article_category','remark' => 'max:100','pid' => 'required|numeric'],['name.required' => '请填写分类名!','name.unique' => '改分类名已存在','remark.max' => '分类简介不能超过100个字符','pid.numeric' => '分类id必须为数字']);// 获取分类名$this->_category->name = $request->input('name');// 获取分类父id,默认是0,为一级分类$this->_category->pid = $request->input('pid',0);// 分类简介$this->_category->remark = $request->input('remark');// 写入数据库$result = $this->_category->save();// 返回结果$result = $result ? '操作成功' : '操作失败';return back()->with('act_msg',$result);
}

获取分类列表

/*** 加载视图* @return [type] [description]*/
public function classify()
{    // 从数据库获取所有分类记录$node = $this->_category->orderBy('id','asc')->get();// 将分类以及子分类整理排序$node = $this->_treeNode($node->toArray(),0);// 加载视图及分配数据return view('admin.classify',['list'=>$node]);
}/*** 整理排序所有分类* @param  array   $data       从数据库获取的分类* @param  integer $parentId 父id,默认一级分类* @return array */
private function _treeNode($data,$parentId = 0)
{// 用于保存整理好的分类节点$node = [];// 循环所有分类foreach ($data as $key => $value) {// 如果当前分类的父id等于要寻找的父id则写入$node数组,并寻找当前分类id下的所有子分类if($parentId == $value ['pid']) {$node [$key] = $value;$node [$key] ['childer'] = $this->_treeNode($data,$value ['id']);}}return $node;
}    

方法classify是用于从数据库获取所有分类以及显示模板。方法_treeNode是一个递归函数。将从数据库获取的所有分类整理排序。排序好的效果如下图:

图片描述

渲染视图

<table class="table table-border table-bordered table-bg table-hover table-sort"><thead><tr class="text-c"><th width="25"><input type="checkbox" name="" value=""></th><th width="80">ID</th><!-- <th>标题</th> --><th width="120">分类名</th><th width="80">简介</th><!-- <th width="80">来源</th> --><th width="120">更新时间</th><th width="60">发布状态</th><th width="120">操作</th></tr></thead><tbody><!--遍历数据-->@foreach($list as $val)<tr class="text-c"><td><input type="checkbox" value="" name=""></td><td>{{$val ['id']}}</td><td class="text-l"><u title="查看">{{$val ['name']}}</u></td><td>{{$val ['remark']}}</td><td>{{$val ['updated_at']}}</td><td>@if($val ['statu'] == 'y')<span class="label label-success radius">启用</span> @else <span class="label label-danger radius">禁用</span> @endif</td><td class="f-14 td-manage"><a><i class="Hui-iconfont">&#xe6de;</i></a><a><i class="Hui-iconfont">&#xe6df;</i></a><a title="删除"><i class="Hui-iconfont">&#xe6e2;</i></a></td></tr><!--判断该分类下是否有子分类-->@if(!empty($val ['childer'])){{get_childer_node($val ['childer'])}}@endif@endforeach</tbody></table>

渲染视图时需要判断该分类下是否有子分类,如果只做到三级分类,此时只需要再来个二层循环就ok了。这边我自定义了一个递归函数get_childer_node 用于获取该分类下的子分类。具体实现如下:

/*** 获取子节点* @param  array  $data [description]* @return [type]       [description]*/
function get_childer_node($data = [])
{// 记录该分类的深度static $callNum = 1;if(empty($data)) return;foreach ($data as $key => $val) {if($val ['statu'] == 'y')$isShow = '<span class="label label-success radius">启用</span>';else$isShow = '<span class="label label-danger radius">禁用</span>';echo <<<HTML<tr class="text-c"><td><input type="checkbox" value="" name=""></td><td>{$val ['id']}</td><td class="text-l">|----{$val ['name']}</span></td><td>{$val ['remark']}</td><td>{$val ['updated_at']}</td><td>$isShow</td><td><a><i class="Hui-iconfont">&#xe6df;</i></a><a><i class="Hui-iconfont">&#xe6e2;</i></a></td></tr>HTML;// 如果该分类的依旧有子分类则再次遍历输出 if(!empty($val ['childer'])) {$callNum ++;get_childer_node($val ['childer']);}// 重置分类层级$callNum = 1;}
}

最终效果

图片描述

相关文章:

软件测试培训怎么学?有没有发展前景?

软件测试是最近几年广受大家关注的一个编程技术&#xff0c;软件测试的出现也是因软件的存在而存在的&#xff0c;目前很多人都想知道软件测试培训怎么学?有没有发展前景?我们来看看下面的详细介绍。 软件测试需要学测试环境(网络环境&#xff0c;windows环境等)、数据库管理…

LeetCode实战:最长有效括号

题目英文 Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring. Example 1: Input: "(()" Output: 2 Explanation: The longest valid parentheses substring is "(…

Android选项卡置底的方法

发现很多Android应用的选项卡 都是显示在页面底部的&#xff0c;网上有资料&#xff1a;通过反射获取TabWidget中的私有变量&#xff0c;改变其值。今天反编译了腾讯微薄&#xff0c;发现实现这个很简单, 只需将布局文件中<TabWidget />标签加个android:layout_gravity&…

【iCore4 双核心板_ARM】例程十七:USB_MSC实验——读/写U盘(大容量存储器)

实验方法&#xff1a; 1、将跳线冒跳至USB_UART,通过Micro USB 线将iCore4 USB-UART接口与电脑相连。 2、打开PUTTY软件。 3、通过读U盘转接线将U盘&#xff08;或者读卡器&#xff09;与iCore4 USB-OTG接口相连。大容量存储器为FAT32格式。 实验现象&#xff1a; 核心代码&…

软件测试技术篇:UI自动化到底是难是易?

UI自动化技术&#xff0c;是我们测试工程师绕不开的一个话题&#xff0c;只要提起它来&#xff0c;基本所有测试工程师都能给你说道说道。 有些人认为它很难&#xff0c;有些人认为它很简单。认为它很难的人会告诉你&#xff0c;UI自动化非常不稳定&#xff0c;太难了&#xff…

获取DataRow某列的值的封装

public class DataHelper{const string DEFSTR "";/// <summary>/// 根据一个类型&#xff0c;获取其默认值&#xff0c;数字默认是为0&#xff0c;字符串默认值为一个空字符串/// </summary>/// <typeparam name"T"></typeparam>…

LeetCode实战:逆波兰表达式求值

题目英文 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are , -, *, /. Each operand may be an integer or another expression. Note: Division between two integers should truncate toward zero.The given RPN expre…

Python函数式编程-map/reduce

1.map map()传入的第一个参数是f&#xff0c;即函数对象本身。 map()函数接收两个参数&#xff0c;一个是函数&#xff0c;一个是Interable&#xff0c;map将传入的函数依次作用到序列的每个元素&#xff0c;并把结果作为新的Iterator返回。 >>> def f(x): ... re…

Java程序员到什么级别可以去BAT上班?

学习java技术&#xff0c;很多人都想要进入到IT行业&#xff0c;如果跳槽到BAT大厂上班&#xff0c;那更是非常好的&#xff0c;近几年学习java技术的人越来越多&#xff0c;那么Java程序员到什么级别可以去BAT上班?来看看下面的详细介绍。 Java程序员到什么级别可以去BAT上班…

Android开发之SharedPreferences的封装

对于大部分初学者来说&#xff0c;如果想利用SharedPreferences进行数据存储的话大部分人(包括本人)应该会这样&#xff1a; 存储&#xff1a; SharedPreferences sharedPreferences getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); Editor editor …

LeetCode实战:设计循环双端队列

题目英文 Design your implementation of the circular double-ended queue (deque). Your implementation should support following operations: MyCircularDeque(k): Constructor, set the size of the deque to be k.insertFront(): Adds an item at the front of Deque…

ItemsControl 解析

先上个示例 <ItemsControl Margin"10" ItemsSource"{Binding}" Name"itemsControl"> <ItemsControl.Template><ControlTemplate TargetType"{x:Type ItemsControl}"><Border CornerRadius"5">&l…

【Web前端培训基础知识】ES5及ES6this详解

今天&#xff0c;我们学习一下JavaScript中的this。我们从什么是this,ES5及ES6中this的几种情况进行学习。让this变的so easy&#xff0c;我们这里说的都是非严格模式下。 什么是this this表示当前行为执行的主体&#xff0c;在javaScript中this不是函数独有的&#xff0c;但是…

LeetCode实战:滑动窗口最大值

题目英文 Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sli…

Partial Class部分类

Partial Class &#xff0c;部分类 或者分布类。顾名思义&#xff0c;就是将一个类分成多个部分。比如说&#xff1a;一个类中有3个方法&#xff0c;在VS 2005将该类中3个方法分别存放在3个不同的.cs文件中。这样做的好处&#xff1a;1、一个大型的项目类可以同时分成不同的区块…

表格中td限宽溢出以省略号代替

table.ms-listviewtable {table-layout:fixed;width: 100%; } table.ms-listviewtable td[role"gridcell"]{white-space:nowrap;text-overflow:ellipsis;-moz-text-overflow: ellipsis;overflow:hidden; } 转载于:https://www.cnblogs.com/JaneBlog/p/7490445.html

【UI设计培训基础知识】设计中的点线面-线

UI设计所要学习的知识有很多&#xff0c;想要在后期的工作中稳稳当当&#xff0c;基础知识一定要扎实&#xff0c;下面就是小编为大家整理的一份关于UI设计培训基础知识的相关内容&#xff0c;主要讲的是设计中的点线面-线&#xff0c;来看看下面的详细资料吧。 点的移动形成一…

场面话大全,绝对受用一生

◆ 父母生日祝酒辞 尊敬的各位领导、各们长辈、各们亲朋好友&#xff1a;大家好&#xff01; 在这喜庆的日子里&#xff0c;我们高兴地迎来了敬爱的父亲&#xff08;母亲&#xff09;XX岁的生日。今天&#xff0c;我们欢聚一堂&#xff0c;举行父亲&#xff08;母亲&#xff09…

LeetCode实战:爬楼梯

题目英文 You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Example 1: Input: 2 Output: 2 Exp…

Visual Studio Remote Debugger(for 2005/2008) .net远程调试转

我采用虚机的方式模拟了局域网环境&#xff0c;以下是我操作的步骤&#xff08;client代表客户端&#xff0c;server代表调试机&#xff09;&#xff1a; 建立ASP.NET项目(client)&#xff1a;简单写了点Code 代码 1 protectedvoidPage_Load(objectsender, EventArgs e)2 {3 in…

UI设计师必备技能,看看你都学会了吗?

想要成为一名合格的UI设计师&#xff0c;是要有这几项必备技能的&#xff0c;学会这些必备技能&#xff0c;那么后期的工作会进行的相当顺利&#xff0c;下面小编就为大家详细的介绍一下UI设计师必备技能都有哪些? UI设计师必备技能&#xff0c;看看你都学会了吗? 1、设计软件…

CSS中关于清除浮动的问题

1.采用:after的方法清除浮动 优点&#xff1a;避免在html里插入多余的标签 详情&#xff1a;http://www.positioniseverything.net/easyclearing.html 整理成一个通用的.clearfix .clearfix:after {content:".";display:block;height:0;clear:both;visibility:hidden…

LeetCode实战:x 的平方根

题目英文 Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. …

Vue中组件数据的传递

Vue中组件的作用域是隔离的&#xff0c;父组件中的数值子组件看不到&#xff01;也就是说&#xff0c;用angular作比喻&#xff0c;组件的scope天生是scope:()的&#xff01;如果父组件需要往子组件中传数据&#xff0c;此时应该使用标签属性&#xff1a; <div id"app&…

学习Python往哪个方向发展好

Python近几年在IT行业的发展前景是非常可观的&#xff0c;尤其是在人工智能领域这一块&#xff0c;吸引了很多人的关注&#xff0c;但不仅仅是人工智能领域&#xff0c;Python在很多其他地方也是非常有发展前景的&#xff0c;那么具体学习Python往那个方向发展好呢?来看看下面…

开发人员绩效考核中有效bug数的统计

我们都知道,开发人员的考核中,bug这块占了一定的比重,那么我们在统计每个开发人员的bug数时,显然要做到有效,不能把缺陷管理系统上的bug不经过处理,就直接进行统计. 如何统计有效bug数呢? 我们从bug的属性上进行控制,分析如下: bug问题来源: 需求问题架构问题设计问题编码问题…

LeetCode实战:反转字符串

题目英文 Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. You may assume al…

HTML5 监听当前位置

2019独角兽企业重金招聘Python工程师标准>>> <!DOCTYPE html> <html><head><meta charset"UTF-8"><title>监听当前位置</title><meta name"viewport" content"widthdevice-width, initial-scale1,…

Python培训教程之Python基础知识点梳理

Python语言是入门IT行业比较快速且简单的一门编程语言&#xff0c;学习Python语言不仅有着非常大的发展空间&#xff0c;还可以有一个非常好的工作&#xff0c;下面小编就来给大家分享一篇Python培训教程之Python基础知识点梳理。 Python培训教程之Python基础知识点梳理&#x…

技术图文:如何通过挂单刷 BigOne 的贡献值?

背景 这段时间 BigOne 开启了「挂单捡钱七天乐」活动&#xff0c;凡在活动期间进行有效挂单的用户均可获得「贡献值」奖励。 详细情况如下&#xff1a; 1. 参与交易对 BTC/USDT, EOS/USDT, ETH/USDT, ONE/USDT, EOS/BTC, ETH/BTC, EOS/ETH&#xff0c;共 7 个交易对。 2. …