php实现无限级分类及下拉菜单树形效果。

PHP开发 | 2016-06-04 10:10:06 | 23978次阅读 | 1评

分类表必须有三个字段:id, parent_id, name

function make_tree($arr){
	if(!function_exists('make_tree1')){
		function make_tree1($arr, $parent_id=0){
			$new_arr = array();
			foreach($arr as $k=>$v){
				if($v->parent_id == $parent_id){
					$new_arr[] = $v;
					unset($arr[$k]);
				}
			}
			foreach($new_arr as &$a){
				$a->children = make_tree1($arr, $a->id);
			}
			return $new_arr;
		}
	}
	return make_tree1($arr);
}

function make_tree_with_namepre($arr)
{
	$arr = make_tree($arr);
	if (!function_exists('add_namepre1')) {
		function add_namepre1($arr, $prestr='') {
			$new_arr = array();
			foreach ($arr as $v) {
				if ($prestr) {
					if ($v == end($arr)) {
						$v->name = $prestr.'└─ '.$v->name;
					} else {
						$v->name = $prestr.'├─ '.$v->name;
					}
				}

				if ($prestr == '') {
					$prestr_for_children = '  ';
				} else {
					if ($v == end($arr)) {
						$prestr_for_children = $prestr.'   ';
					} else {
						$prestr_for_children = $prestr.'│  ';
					}
				}
				$v->children = add_namepre1($v->children, $prestr_for_children);

				$new_arr[] = $v;
			}
			return $new_arr;
		}
	}
	return add_namepre1($arr);
}

/**
 * @param $arr
 * @param int $depth,当$depth为0的时候表示不限制深度
 * @return string
 */
function make_option_tree_for_select($arr, $depth=0)
{
	$arr = make_tree_with_namepre($arr);
	if (!function_exists('make_options1')) {
		function make_options1($arr, $depth, $recursion_count=0, $ancestor_ids='') {
			$recursion_count++;
			$str = '';
			foreach ($arr as $v) {
				$str .= "<option value='{$v->id}' data-depth='{$recursion_count}' data-ancestor_ids='".ltrim($ancestor_ids,',')."'>{$v->name}</option>";
				if ($v->parent_id == 0) {
					$recursion_count = 1;
				}
				if ($depth==0 || $recursion_count<$depth) {
					$str .= make_options1($v->children, $depth, $recursion_count, $ancestor_ids.','.$v->id);
				}

			}
			return $str;
		}
	}
	return make_options1($arr, $depth);
}

效果图:

屏幕快照 2016-06-04 10.04.21.png (上传于2016-06-04 10:10:06)
屏幕快照 2016-06-04 10.04.21.png


博友评论,共1条
Avatar
1楼: 静夜思 发表于 2016-06-07 10:03   回复
获得祖先链:
function get_ancestors($arr, $e)
{
    $ancestors = array();
    foreach ($arr as $a) {
        if ($a->id == $e->parent_id) {
            $ancestors[] = $a;
            if ($a->parent_id != 0) {
                $ancestors = array_merge(get_ancestors($arr, $a), $ancestors);
            }
        }
    }
    return $ancestors;
}
浏览1528971次
最新评论