PHP 无限级分类树

1、

function generateTree($items){
    $tree = array();
    foreach($items as $item){
        if(isset($items[$item['pid']])){
            $items[$item['pid']]['son'][] = &$items[$item['id']];
        }else{
            $tree[] = &$items[$item['id']];
        }
    }
    return $tree;
}
$items = array(
    1 => array('id' => 1, 'pid' => 0, 'name' => '安徽省'),
    2 => array('id' => 2, 'pid' => 0, 'name' => '浙江省'),
    3 => array('id' => 3, 'pid' => 1, 'name' => '合肥市'),
    4 => array('id' => 4, 'pid' => 3, 'name' => '长丰县'),
    5 => array('id' => 5, 'pid' => 1, 'name' => '安庆市'),
);
print_r(generateTree($items));

2、

function getTree($data, $pId=0)
{
  $tree = '';
  foreach($data as $k => $v){
    if($v['pid'] == $pId){

       //父亲找到儿子
      $v['pid'] = getTree($data, $v['id']);
      $tree[] = $v;
      //unset($data[$k]);
    }
  }
  return $tree;
}

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

上一篇:CYQ.Data 轻量数据层之路 使用篇二曲 MAction 数据查询(十三)----002


下一篇:iOS常用小功能