无限极分类(一)获得树结构

数据表结构

 

函数:

function make_tree($list,$pk='id',$pid='pid',$child='_child',$root=0){
  $tree=array();
  $packData=array();

  //转换数组的结构
  foreach ($list as $data) {
    $packData[$data[$pk]] = $data;
  }
  foreach ($packData as $key =>$val){
    if($val[$pid]==$root){//代表跟节点
      $tree[]=& $packData[$key];
    }else{
      //找到其父类
      $packData[$val[$pid]][$child][]=& $packData[$key];
    }
  }
  return $tree;
}

$arr = make_tree($list, 'cat_id', "parent_id", "son", 0);

var_dump($arr);

结果:

array(5) {
  [0] => array(6) {
    ["cat_id"] => string(1) "1"
    ["cat_name"] => string(6) "女装"
    ["parent_id"] => string(1) "0"
    ["sort_order"] => string(2) "50"
    ["is_show"] => string(1) "1"
    ["son"] => array(3) {
      [0] => array(6) {
        ["cat_id"] => string(1) "6"
        ["cat_name"] => string(9) "连衣裙"
        ["parent_id"] => string(1) "1"
        ["sort_order"] => string(2) "50"
        ["is_show"] => string(1) "1"
        ["son"] => array(1) {
          [0] => array(5) {
            ["cat_id"] => string(2) "31"
            ["cat_name"] => string(12) "我的最爱"
            ["parent_id"] => string(1) "6"
            ["sort_order"] => string(2) "50"
            ["is_show"] => string(1) "1"
          }
        }
      }
.....

 


 

posted @ 2017-01-02 15:49  cat_crazy  阅读(2530)  评论(0编辑  收藏  举报