ツリー配列の作成

11662 ワード

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'=>'   ','pid'=>3),
    array('id'=>9,'name'=>'m3   ','pid'=>8),

);


//        
function category($arr,$pid=0,$level=0){
    //        ,       ,     ,            ,         ,          ,   ,             ,          
    //       
    static $list=array();
    //pid=0    foreach($arr as $key => $value){
        //      pid=0,       ,         
        if($value['pid']==$pid){
            //        
            $arr['level']=$level;

            $flg = str_repeat('000',$level);
            $value['name'] = $flg.$value['name'];

            $list[]=$value;
            unset($arr[$key]);
            //   ,    ,        id+1
            category($arr,$value['id'],$level+1);
        }
    }
    return $list;//    
}
echo "
"
;
print_r(category($categories));