首页 > 代码库 > 设计树状结构货品分类状态

设计树状结构货品分类状态

 1 <?php 2 header(‘Content-Type:text/html; charset=utf-8‘); 3 $mp = array( 4     ‘name‘ => ‘手机‘, ‘children‘ => array( 5         array(‘name‘ => ‘非智能机‘), 6         array(‘name‘ => ‘智能机‘, ‘children‘ =>array( 7             array(‘name‘ => ‘安卓机‘), 8             array(‘name‘ => ‘苹果机‘), 9             array(‘name‘ => ‘WP机‘)10         ))11     )12 );13 14 $cp =array(15     ‘name‘ => ‘电脑‘, ‘children‘ => array(16         array(‘name‘ => ‘电脑整机‘, ‘children‘ => array(17             array(‘name‘ => ‘笔记本‘),18             array(‘name‘ => ‘超极本‘),19             array(‘name‘ => ‘游戏本‘)20         )),21         array(‘name‘ => ‘电脑配件‘, ‘children‘ => array(22             array(‘name‘ => ‘CPU‘),23             array(‘name‘ => ‘主板‘)24         ))25     )26 );27 28 $goodsCats = array($mp, $cp);29 30 //递归遍历$goodsCat中的所有元素31 function tree($goodsCats, $deep=0){32     //1:定义一个容器装所有的分类33     static $tree = array();34     //2:定义一个变量来记录分类的级别35     ++$deep;36     foreach($goodsCats as $goodsCat){37         $treeCat = array(‘name‘ => $goodsCat[‘name‘]);  //将分类名字存放到数组中38         $treeCat[‘deep‘] = $deep;                       //将分类级别也存放到数组中39         $tree[] = $treeCat;                             //将每次循环的分类存放起来40         //检查每个分类下是否有子分类,如果有,继续遍历41         if(isset($goodsCat[‘children‘])){42             tree($goodsCat[‘children‘],$deep);43         }44     }45      return $tree;46 }47 48 $treeData = tree($goodsCats);49 50 foreach($treeData as $catData){51     echo str_repeat(‘------‘,($catData[‘deep‘]-1)).$catData[‘name‘]."<br/>";52 }
View Code

 

设计树状结构货品分类状态