php产品分类两种办法实现
原创方式一:
namespace App\Http\Controllers;
class InfiniteController extends Controller
{
//路径方式实现无限级
public function wuxianji(){
$rows = [
[
id => 1,
name => 一类目,
pid => 0,
path => 0
],
[
id => 2,
name => 二类目,
pid => 0,
path => 0
],
[
id => 3,
name => 小一类目,
pid => 1,
path => 0-1
],
[
id => 4,
name => 小二类目,
pid => 2,
path => 0-2
],
[
id => 5,
name => 小小一类目,
pid => 3,
path => 0-1-3
],
];
foreach ($rows as &$row){
$num = substr_count($row[path], -);
if($row[pid] > 0){
$pre = |.str_repeat(-, $num);
}else{
$pre = ;
}
$row[tree] = $pre.$row[name];
}
foreach ($rows as $row2){
$arr[] = $row2[path].-.$row2[id];
}
array_multisort($arr,$rows);
foreach ($rows as $row3){
echo "
{$row3[tree]}
";}
//dd($arr);
}
}
方式二:
递归方式
$rows = [
[
id => 1,
name => 一类目,
pid => 0,
path => 0
],
[
id => 2,
name => 二类目,
pid => 0,
path => 0
],
[
id => 3,
name => 小一类目,
pid => 1,
path => 0-1
],
[
id => 4,
name => 小二类目,
pid => 2,
path => 0-2
],
[
id => 5,
name => 小小一类目,
pid => 3,
path => 0-1-3
],
];
$trees = buildTree(0);
$str = showLeimu($trees);
echo $str;
function findChild(&$arr,$id){
$childs = [];
foreach ($arr as $k=>$v){
if($v[pid] == $id){
$childs[] = $v;
}
}
return $childs;
}
function buildTree($root_id){
global $rows;
$childs = findChild($rows, $root_id);
if(empty($childs)){
return null;
}
foreach ($childs as $k=>$v){
$rescurTree = buildTree($v[id]);
if(null != $rescurTree){
$childs[$k][childs] = $rescurTree;
}
}
return $childs;
}
function showLeimu($trees){
foreach ($trees as $tree){
if($tree[pid] > 0){
$pre = |.str_repeat(-, substr_count($tree[path], -));
}
$str.= $pre.$tree[name].
;
if(isset($tree[childs])){
$str.=showLeimu($tree[childs]);
}
}
return $str;
}
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除