PHP菜单:用于父项的循环

时间:2015-03-19 16:39:05

标签: php database drop-down-menu pdo do-while

我正在尝试使用PHP并创建一个PHP菜单,该菜单使用存储在数据库中的项目和PHP代码以正确的顺序构建菜单项。可以更改数据库上的值,因此我希望首先导出父项,然后在下面添加嵌套项。

我想使用循环(do-while?我猜)从数据库中获取数据,这样我就可以使用嵌套项正确排列菜单,并输出我想要使用的类。

我的数据库表存储每个项目的标题和网址,嵌套项目包含父项目的ID,父项目的id为0设置为父项,如下所示:

--------------------
| id     | int(11) |  
--------------------
| title  | varchar |  
--------------------
| url    | varchar |  
--------------------
| parent | int(11) |  
--------------------

这是我的PHP代码:

try {
    $stm = $db->prepare('SELECT * FROM menu');
    $stm->execute();
    $result = $stmt->fetchAll();

     // requested loop / function

    }

输出应如下所示:

$menu = menu::create()
    ->add('Homepage', '/', menu::create()
    ->add('Item1', '/item1/', menu::create()
        ->add('Subitem1', '/subitem1/')
        ->add('Subitem1', '/subitem1/')
    ->add('Item2', '/item2/', menu::create()
        ->add('Subitem3', '/subitem3/')
        ->add('Subitem4', '/subitem4/')

请建议如何使用数据库项获得此输出... 谢谢。

1 个答案:

答案 0 :(得分:0)

必须做一些调整,但我希望这会给你一个领导

function    sort_parent($parent)
{
    $j=0;
    $flag = true;
    $temp=0;
    while ( $flag )
    {
        $flag = false;
        for( $j=0;  $j < count($parent)-1; $j++)
        {
            if ($parent[$j]->id > $parent[$j+1]->id)
            {
                $temp = $parent[$j]->id;
                $parent[$j] = $parent[$j+1]->id;
                $parent[$j+1]->id = $temp;
                $flag = true;
            }
        }
    }
    return ($parent);
}

function    sort_children($children)
{
    $j=0;
    $flag = true;
    $temp=0;
    while ( $flag )
    {
        $flag = false;
        for( $j=0;  $j < count($children)-1; $j++)
        {
            if ($children[$j]->parent > $children[$j+1]->parent)
            {
                $temp = $children[$j]->parent;
                $children[$j] = $children[$j+1]->parent;
                $children[$j+1]->parent = $temp;
                $flag = true;
            }
        }
    }
    return ($children);
}

try {
    //First we fetch the parents
    $stm = $db->prepare('SELECT * FROM menu WHERE parent = 0');
    $stm->execute();
    $parent = $stmt->fetchAll();

    // Then the childrens. Note: In some versions of SQL this operator may be written as !=
    $stm = $db->prepare('SELECT * FROM menu WHERE parent <> 0');
    $stm->execute();
    $children = $stmt->fetchAll();
}

    // We sort parent and children with a basic buble sort
    $parent = sort_parent($parent);
    $children = sort_object($children);

    // To finish as Parent and Children are in the same order we can do that
    foreach ($parent as $parent_menu_item) {
        $menu = menu::create() -> add($parent_menu_item->title, $parent_menu_item->url);
        for ($j=0; $children[$i]->parent == $parent_menu_item->id; j++)
        {
            $menu = menu::create() -> add($children[$j]->title, $children[$j]->url);
        }
    }

有帮助吗?