//配合下面方法用 不需直接调用
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->pid == $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
* default 默认选择的id
*/
function make_option_tree_for_select($arr, $default, $depth = 0) {
$arr = make_tree_with_namepre($arr);
if (!function_exists('make_options1')) {
function make_options1($arr, $default, $depth, $recursion_count = 0, $ancestor_ids = '') {
$recursion_count++;
$str = '';
foreach ($arr as $v) {
$value = "";
if ($v->id == $default) {
$value = "selected=selected";
}
$str .= "<option value='{$v->id}' data-depth='{$recursion_count}' data-ancestor_ids='" . ltrim($ancestor_ids, ',') . "' {$value}>{$v->name}</option>";
if ($v->pid == 0) {
$recursion_count = 1;
}
if ($depth == 0 || $recursion_count < $depth) {
$str .= make_options1($v->children,$default, $depth, $recursion_count, $ancestor_ids . ',' . $v->id);
}
}
return $str;
}
}
return make_options1($arr, $default, $depth);
}
下拉菜单 ---树状展现
最新推荐文章于 2024-07-23 17:35:39 发布