日期:2014-05-17 浏览次数:20513 次
usage: php tree-display.php <tree deepth>
$ php tree-display.php 3 name-00000001[1] ┇ ┠ name-00000002[2] ┇ ┇ ┠ name-00000003[3] ┇ ┇ ┠ name-00000004[4] ┇ ┇ ┗ name-00000005[5] ┇ ┠ name-00000006[6] ┇ ┇ ┠ name-00000007[7] ┇ ┇ ┠ name-00000008[8] ┇ ┇ ┗ name-00000009[9] ┇ ┗ name-00000010[10] ┇ ┠ name-00000011[11] ┇ ┠ name-00000012[12] ┇ ┗ name-00000013[13] ┠ name-00000014[14] ┇ ┠ name-00000015[15] ┇ ┇ ┠ name-00000016[16] ┇ ┇ ┠ name-00000017[17] ┇ ┇ ┗ name-00000018[18] ┇ ┠ name-00000019[19] ┇ ┇ ┠ name-00000020[20] ┇ ┇ ┠ name-00000021[21] ┇ ┇ ┗ name-00000022[22] ┇ ┗ name-00000023[23] ┇ ┠ name-00000024[24] ┇ ┠ name-00000025[25] ┇ ┗ name-00000026[26] ┗ name-00000027[27] ┠ name-00000028[28] ┇ ┠ name-00000029[29] ┇ ┠ name-00000030[30] ┇ ┗ name-00000031[31] ┠ name-00000032[32] ┇ ┠ name-00000033[33] ┇ ┠ name-00000034[34] ┇ ┗ name-00000035[35] ┗ name-00000036[36] ┠ name-00000037[37] ┠ name-00000038[38] ┗ name-00000039[39] resource usage[level: 3, node number: 39]: clock time: 0.001967s system cpu: 0.000169s user cpu: 0.001013s memory usage: 7208 byte
<?php /** * 无限级(受尾节点描述算法限制, 详见tree_parse注释)递归菜单 * author: selfimpr * blog: http://blog.csdn.net/lgg201 * mail: lgg860911@yahoo.com.cn */ define('MAX_NODES', 3); /* 最大子节点数 */ define('MAX_NODE_INDEX', MAX_NODES - 1); /* 子节点最大索引值 */ define('NAME_FMT', 'name-%08d'); /* 节点内容输出格式串 */ /* 树节点数据结构 */ define('K_ID', 'id'); define('K_NAME', 'name'); define('K_CHILD', 'children'); /* 输出构造时使用的拼装字符 */ define('PREFIX_TOP', '┏'); /* 第一层第一个节点的标识符 */ define('PREFIX_BOTTOM', '┗'); /* 每一个父节点的最后一个子节点的标识符 */ define('PREFIX_MIDDLE', '┠'); /* 所有非上面两种情况的节点的标识符 */ define('PREFIX_LINE', '┇'); /* 祖先节点的连线符 */ define('SPACE', ' '); /* 空白占位(所有尾节点不显示连线符) */ define('WIDE_SPACE', str_repeat(SPACE, 4)); /* 宽的空白占位, 为了让树的层次清晰 */ /** * data_build * 构造一个节点 * @param mixed $id 节点id * @param mixed $is_leaf 是否叶子 * @access public * @return void */ function node_build($id, $is_leaf = FALSE) { return array( K_ID => $id, K_NAME => sprintf(NAME_FMT, $id), K_CHILD => $is_leaf ? NULL : array(), ); } /** * tree_build * 构造一棵树(树中每个节点的子节点数由MAX_NODES确定) * @param mixed $datas 要返回的树引用 * @param mixed $id 起始ID * @param mixed $level 树的层级 * @access public * @return void */ function tree_build(&$datas, &$id, $level) { if ( $level < 1 ) return ; $is_leaf = $level == 1; $i = -1; $next_level = $level - 1; while ( ++ $i < MAX_NODES ) { $data = node_build($id ++, $is_leaf); if ( !$is_leaf ) tree_build($data[K_CHILD], $id, $next_level); array_push($datas, $data); } } /** * node_str * 输出一个节点自身的信息 * @param mixed $string 返回结果的字符串(引用传值) * @param mixed $data 节点数据 * @access public * @return void */ function node_str(&$string, $data) { $string .= sprintf(' %s[%