从邻接列表模型数据库中检索数据。(MySQL)

时间:2012-10-27 14:57:06

标签: php mysql codeigniter

function get_hierarchy_page()
{
    $detail = $this->input->post('name');
    $tree = $this->dashboard_model->get_detail($detail);
    $this->load->view('layout/layout', $data);

    if(isset($tree))
    {
        $data['hierarchy'] = $this->data_array_for_teacher($tree);
    }
}

function data_array_for_teacher($tree)
{
    if(!(isset($tree)))
        return 0;

    $data_query = mysql_query("select * from tbl_level");

    while($result = mysql_fetch_assoc($data_query))
    {
        $id = $result['level_id'];
        $data_array[$id] = $result;
    }

    //array to get level id
    while($level_result = mysql_fetch_assoc($tree))
    {
        $level_array[] = $level_result['level_id'];
    }

    if(!(isset($level_array)))
        return 0;

    foreach($level_array as $level)
    {
        $p   = $this->recursive_for_teacher($data_array,$level);    
        print_r($p);
    }
}

function recursive_for_teacher($data_array,$level_once)
{
    if(!isset($data_array,$level_once))
        return 0;

    $i = 0;
    static $p = array();
    $data = $data_array;
    $y = $level_once;
    $x = $data[$y]['level_parent'];
    $z = $data[$y]['level_name'];
    $y=$x;
    array_push($p,$z);
    $p[] = $z;

    if($y!=0)
        $this->recursive_for_teacher($data,$y);

    return $p;
}

我正在研究一个基于使用邻接列表模型存储在mysql中的分层数据的系统。我有2个表tbl_usertbl_level
tbl_level包含以下字段:level_idlevel_parentlevel_name。这三个字段分别与标准数据库结构中的idparent_nameparent_id相同。

在表tbl_level中,有许多组织,每个组织都有不同的层次结构 我写了上面的代码,解决了我在给定组织中获得任何权限的整个层次结构的问题 我现在面临的唯一问题是当我在一个阵列中得到所需的答案时 每个权威我需要一个数组 Array(     
[0] => Engineering and Technology
    [1] => Univ1
    [2] => Class
    [3] => Master of Business Administration
    [4] => Engineering and Technology
    [5] => univ1
    [6] => Class_cse
    [7] => Computer Science
    [8] => Bachelor of Technology
    [9] => Engineering and Technology
    [10] => univ1
)

有人能为这个问题提出更好的解决方案吗?

1 个答案:

答案 0 :(得分:1)

function parent_sort($categories)
{    
    foreach($categories as $item)
        $childs[$item->parent_id][] = $item;
    foreach($categories as $item) 
        if (isset($childs[$item->category_id]))
            $item->childs = $childs[$item->category_id];

    return $childs[0];
}

您可以使用此函数对水平数组进行排序,它将按级别输出排序数组