Controller
//组织架构
public function index()
{
header("content-type:text/html;charset=utf-8");
$company_id = I('company_id');
$categories = M()->query("select id,name as text,org_parent_id from company_org where company_id = '$company_id' and state !=2");// company_id = '$company_id'
//,org_level,org_parent_id,company_id,department_manager_id,fanli_money_percent
//var_dump($categories);die();
/*======================非递归实现========================*/
$tree = array();
//第一步,将分类id作为数组key,并创建children单元
foreach ($categories as $category) {
$tree[$category['id']] = $category;
$tree[$category['id']]['children'] = array();
}
//第二步,利用引用,将每个分类添加到父类children数组中,这样一次遍历即可形成树形结构。
foreach ($tree as $key => $item) {
if ($item['org_parent_id'] != 0) {
$tree[$item['org_parent_id']]['children'][] = &$tree[$key];//注意:此处必须传引用否则结果不对
//$tree['children'][] = &$tree[$key];//注意:此处必须传引用否则结果不对
/*
if($tree[$key]['children'] == null){
unset($tree[$key]['children']); //如果children为空,则删除该children元素(可选)
}
*/
}
}
////第三步,删除无用的非根节点数据
foreach ($tree as $key => $category) {
if ($category['org_parent_id'] != 0) {
unset($tree[$key]);
}
}
apiReturnMsg(1, '组织架构', $tree);
}
Html JS遍历
<script src="__PUBLIC__/static/js/jquery-2.1.0.min.js"></script>
<script src="__PUBLIC__/static/js/jstree.min.js"></script>
<script type="text/javascript">
$(function() {
//获取数据
var company_id = 1;
var department_id = 80;
var org_level = 2;
getData();
function getData() {
$.ajax({
type: "post",
url: "/index.php/Admin/Org",
async: true,
data: {
company_id: company_id,
department_id: department_id,
org_level: org_level,
},
success: function(res) {
console.log(res);
for(item in res.data){
var _data = res.data[item];
}
$('#html').jstree({
'core': {
'data': _data
}
});
}
});
}
});
</script>
//默认打开树,本例为特殊处理,给结构中state为0的下划线标注
<script>
setTimeout("offline()", 1000 )
//停用用户下划线显示
function offline(){
$('#html').jstree().open_all();
$.ajax({
type: "post",
url: "/index.php/Admin/Org/offlineUserList",
async: true,
data: {
company_id:1,
},
success: function(res) {
//alert(res);
if(res.code == 1){
var offline_list = res.data.list;
console.log(offline_list);
$.each(offline_list,function(n,value) {
var th = value.id;
//alert(th);
var id_name = "#"+th+"_anchor";
$(id_name).css({ "text-decoration": "underline" });
//alert(id_name);
// $("#1_anchor").css({ "text-decoration": "underline" });
});
}
// $("#18_anchor").css({ "text-decoration": "underline" });
}
});
//$("#1_anchor").css({ "text-decoration": "underline" });
}
</script>