thinkphp5.0无限递归操作
ThinkPHP
0000-00-00 00:00:00
PHP无限极分类操作(递归)
初始数据:
$arr = array(
array('id'=>1,'name'=>'电脑','pid'=>0),
array('id'=>2,'name'=>'手机','pid'=>0),
array('id'=>3,'name'=>'笔记本','pid'=>1),
array('id'=>4,'name'=>'台式机','pid'=>1),
array('id'=>5,'name'=>'智能机','pid'=>2),
array('id'=>6,'name'=>'功能机','pid'=>2),
array('id'=>7,'name'=>'超级本','pid'=>3),
array('id'=>8,'name'=>'游戏本','pid'=>3),
);
公共方法:(index.php)
public function getTree($arr,$id){
$list =array();
foreach ($arr as $k=>$v){
if ($v['pid'] == $id){
$v['son'] = $this -> getTree($arr,$v['id']);
$list[] = $v;
}
}
return $list;
}
调用方法:
use app\common\controller\Index as commonIndex;
public function test(){
//引入公用数据
$common = new commonIndex();
$arr = array(
array('id'=>1,'name'=>'电脑','pid'=>0),
array('id'=>2,'name'=>'手机','pid'=>0),
array('id'=>3,'name'=>'笔记本','pid'=>1),
array('id'=>4,'name'=>'台式机','pid'=>1),
array('id'=>5,'name'=>'智能机','pid'=>2),
array('id'=>6,'name'=>'功能机','pid'=>2),
array('id'=>7,'name'=>'超级本','pid'=>3),
array('id'=>8,'name'=>'游戏本','pid'=>3),
);
$array = $common -> getTree($arr,0);
echo '<pre>';
dump($array);
}
返回的数据样式:
array(2) {
[0] => array(4) {
["id"] => int(1)
["name"] => string(6) "电脑"
["pid"] => int(0)
["son"] => array(2) {
[0] => array(4) {
["id"] => int(3)
["name"] => string(9) "笔记本"
["pid"] => int(1)
["son"] => array(2) {
[0] => array(4) {
["id"] => int(7)
["name"] => string(9) "超级本"
["pid"] => int(3)
["son"] => array(0) {
}
}
[1] => array(4) {
["id"] => int(8)
["name"] => string(9) "游戏本"
["pid"] => int(3)
["son"] => array(0) {
}
}
}
}
[1] => array(4) {
["id"] => int(4)
["name"] => string(9) "台式机"
["pid"] => int(1)
["son"] => array(0) {
}
}
}
}
[1] => array(4) {
["id"] => int(2)
["name"] => string(6) "手机"
["pid"] => int(0)
["son"] => array(2) {
[0] => array(4) {
["id"] => int(5)
["name"] => string(9) "智能机"
["pid"] => int(2)
["son"] => array(0) {
}
}
[1] => array(4) {
["id"] => int(6)
["name"] => string(9) "功能机"
["pid"] => int(2)
["son"] => array(0) {
}
}
}
}
}
以上便是所有步骤流程,仁者见仁,智者见智,祝各位码农旗开得胜!
六月初字帖坊小程序
你想要的字帖模板及工具,这里都有!
881篇文章
2551人已阅读