目前见过最高效的无限分类

<?php
header ( 'Content-Type:text/html;charset=utf-8' );
$data = array (
array ('cid' => 26, 'parent_cid' => 0, 'name' => '饭' ),
array ('cid' => 27, 'parent_cid' => 26, 'name' => '米饭' ),
array ('cid' => 28, 'parent_cid' => 27, 'name' => '蛋炒饭' ),
array ('cid' => 29, 'parent_cid' => 28, 'name' => '粗茶淡饭' ),
 );
//两次循环组装array的树形态
function data2tree($data, $root = 0, $cid = 'id', $pid = 'pid', $child = '_child') {
    $tree = array ();
    $_temp = array ();
    foreach ( $data as $key => $val ) {
        $_temp [$val [$cid]] = & $data [$key];
    }
    foreach ( $data as $key => $val ) {
        $parentId = $val [$pid];   //上级id
        if ($root == $parentId) {   //如果上级id 等于根id
            $tree [] = & $data [$key];   //那么 添加到tree里面
        } else {
            if (isset ( $_temp [$parentId] )) {
                $parent = & $_temp [$parentId];
                $parent [$child] [] = & $data [$key];
            }
        }
    }
    return $tree;
}
//递归输出数据
function output($tree) {
    foreach ( $tree as $v ) {
        echo '<li>', $v ['name'];
        if (isset ( $v ['_child'] ))
            echo '<ul>', output ( $v ['_child'] ), '</ul>';
        echo '</li>';
    }
}
$tree = data2tree ( $data, 0, 'cid', 'parent_cid' );
output ( $tree );

 

posted @ 2013-03-25 14:15  维优网络工作室  阅读(212)  评论(0)    收藏  举报