php无限极分类遍历时mysql语句_不用递归 怎么计算无限极分类 php+mysql

展开全部

直接举个例子:<?php

header("content-type:text/html;charset=utf-8");

$categories = 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'=>'游戏本62616964757a686964616fe58685e5aeb931333363393137','pid'=>3),

);

/*======================非递归实现========================*/

$tree = array();

//第一步,将分类id作为数组key,并创建children单元

foreach($categories as $category){

$tree[$category['id']] = $category;

$tree[$category['id']]['children'] = array();

}

//第二步,利用引用,将每个分类添加到父类children数组中,这样一次遍历即可形成树形结构。

foreach($tree as $key=>$item){

if($item['pid'] != 0){

$tree[$item['pid']]['children'][] = &$tree[$key];//注意:此处必须传引用否则结果不对

if($tree[$key]['children'] == null){

unset($tree[$key]['children']); //如果children为空,则删除该children元素(可选)

}

}

}

第三步,删除无用的非根节点数据

foreach($tree as $key=>$category){

if($category['pid'] != 0){

unset($tree[$key]);

}

}

print_r($tree);

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值