使用MySql中的PHP创建数组类别树

时间:2013-12-19 18:41:09

标签: php mysql codeigniter

我正在使用codeigniter进行应用程序,我想知道如果所有数据都在一个表中,如何用php和MySql制作categoire树结构......我正在制作一个菜单。

所以这是我的mysql表示例:

[id_categorie] [categorie_name] [id_parrent]
       1            Mens             0
       2           Women             0      
       3           Jeckets           1
       4           Thights           2
       5           Pants             1

通缉输出是与此类似的数组数组:

Array
(
    [1] => Array
        (
            [id] => 1
            [name] => Mens
            [parent] => 0
            [children] => Array
                (
                    [3] => Array
                        (
                            [id] => 3
                            [name] => Jackets
                            [parent] => 1
                        )

                )

        )

    [2] => Array
        (
            [id] => 2
            [name] => Women
            [parent] => 0
        )

)

所以我可以显示带子项的菜单,比如这个

-Mens  
   -Jeckets  
   -Pants 
-Women
   -Thights

2 个答案:

答案 0 :(得分:1)

有许多不同的方法可以做到这一点。例如,你可以构建一个包含父母的孩子的数组。

/**
 *  All menu items.  This would come from MySQL, for example.
 */
$cats = array(1 => array('id' => 1, 'name' => 'Mens', 'parent' => 0),
              2 => array('id' => 2, 'name' => 'Women', 'parent' => 0),
              3 => array('id' => 3, 'name' => 'Jackets', 'parent' => 1));
$menu = array();
/**
 *  Build array that places children under parents
 */
foreach ( $cats as $k => $v ) {
    if ( isset($v['parent']) && $v['parent'] > 0 ) {
        $menu[$v['parent']]['children'][$k] = $v;   
    } else {
        $menu[$k] = $v;
    }
}

然后通过$ menu循环并构建HTML。

Array
(
    [1] => Array
        (
            [id] => 1
            [name] => Mens
            [parent] => 0
            [children] => Array
                (
                    [3] => Array
                        (
                            [id] => 3
                            [name] => Jackets
                            [parent] => 1
                        )

                )

        )

    [2] => Array
        (
            [id] => 2
            [name] => Women
            [parent] => 0
        )

)

答案 1 :(得分:0)

你会想在php中编写一个递归函数,这是一个你想要修改以适合你的代码的例子。

function getCategoryTree($parentId = 0){

    if($result = $this->database->getCategoryByParentID($parentID)){
        if($result->num_rows){
            while ($resultRow = $result->fetch_array(MYSQLI_ASSOC)) {
                 $resultRow['children'] = $this->getCategoryTree($resultRow['parentID']);
                 $data[] = $resultRow;
            }
        }
    }

    return $data;
}