php无限分类(递归版本)

作者: admin 分类: php 发布时间: 2012-09-08 03:58

Array
(
[0] => Array
(
[id] => 1
[name] => dev
[parentid] => 0
[childs] => Array
(
[0] => Array
(
[id] => 2
[name] => php
[parentid] => 1
[childs] => Array
(
[0] => Array
(
[id] => 3
[name] => smarty
[parentid] => 2
)

[1] => Array
(
[id] => 5
[name] => pdo
[parentid] => 2
[childs] => Array
(
[0] => Array
(
[id] => 6
[name] => pdo-mysql
[parentid] => 5
)

)

)

)

)

[1] => Array
(
[id] => 7
[name] => java
[parentid] => 1
)

)

)

[1] => Array
(
[id] => 4
[name] => life
[parentid] => 0
)

)

 

<?php
$rows = array(
    array(
        'id' => 1,
        'name' => 'dev',
        'parentid' => 0
    ),
    array(
        'id' => 2,
        'name' => 'php',
        'parentid' => 1
    ),
    array(
        'id' => 3,
        'name' => 'smarty',
        'parentid' => 2
    ),
    array(
        'id' => 4,
        'name' => 'life',
        'parentid' => 0
    ),
    array(
        'id' => 5,
        'name' => 'pdo',
        'parentid' => 2
    ),
    array(
        'id' => 6,
        'name' => 'pdo-mysql',
        'parentid' => 5
    ),
    array(
        'id' => 7,
        'name' => 'java',
        'parentid' => 1
    )
);

// 72648
// 84072

function findChild(&$arr,$id){

    $childs=array();
     foreach ($arr as $k => $v){
         if($v['parentid']== $id){
              $childs[]=$v;

         }

    }

    return $childs;

}
function build_tree($root_id){
    global $rows;
    $childs=findChild($rows,$root_id);
    if(empty($childs)){
        return null;
    }
   foreach ($childs as $k => $v){
       $rescurTree=build_tree($v[id]);
       if( null !=   $rescurTree){ 
       $childs[$k]['childs']=$rescurTree;
       }
   }
    return $childs;
}

$tree=build_tree(0);

echo memory_get_usage();

print_r($tree);

?>


function dafenglei_select($m,$id, $fenlei ){
global $menu;
$n = str_pad(”,$m,’-‘,STR_PAD_RIGHT);
$n = str_replace(“-“,”&nbsp;&nbsp;&nbsp;”,$n);
for($i=0;$i<count($fenlei);$i++){

if($fenlei[$i][‘classid’]==$id){
$menu .= “<option value=\””.$fenlei[$i][‘id’].”\”>”.$n.”|—”.$fenlei[$i][‘name’].”</option>\n”;
}
$this->dafenglei_select($m+1,$fenlei[$i][‘id’], $fenlei );
}
}
return $menu;
}

dafenglei_select(0,0, $fenlei );

$fenlei  无限分类数组 $id是选择从哪个分类开始 写0代表顶级开始分,只要把数组放进去就可以分了

 

这样是否会更好些?

$runTime = 0;

function T($data, $keys=array(0), $tmp = array()) {
  global $runTime;
     if(!empty($data)) {
         foreach($data as $k => $d) {
             $pid = $d['pid'];
             $id = $d['id'];
       $name = $d['name'];
             if(in_array($pid, $keys))   {
        $t = array("name" => $name);
        T($data, array($id), &$t);
                $tmp["id:$id"] = $t;
                unset($data[$k]);
             }
         }
     }
  $runTime++;
 }

$tmp = array();
 $t = T($data, array(0), &$tmp);
print_r($tmp);

$num = count($data);
echo "\n------总纪录数为:< $num >  复杂度为:< $runTime >  ------\n";