简体   繁体   中英

PHP & MYSQL: Fetch associative array with levels

So I want to use PHP to build a navigation menu.

The menu items are stored in a database...

Database:

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

The output that i need should look like this:

Desired output:

$menu = array
(
    array
    (
        'title' => 'Item One',
        'url' => 'item_one.php',
    ),
    array
    (
        'title' => 'Item Two',
        'url' => 'item_two.php',
        'children' => array
        (
            array
            (
                'title' => 'Item Three',
                'url' => 'item_three.php',
            ),
            array
            (
                'title' => 'Item Four',
                'url' => 'item_four.php',
            )
        )
    )
);

The function to build the menu should use something like the code below, i'm not sure what i'm doing and I'm trying to use something like this:

Here is my code:

// Connect to database and fetch result.

     $stmt = $db->prepare('SELECT id,parent,title,url FROM nav_menu');
     $stmt->execute();
     $result= $stmt->fetch(PDO::FETCH_ASSOC);   

// Example function that i'm not sure how to use to get the desired output.

    function build($level = NULL)  
    {  
        $level_id = empty($level) ? 0 : $level->id;  

        $level = $this->where('parent', $level_id)->orderby('id', 'asc')->find_all();  

        $menu = new menu;  

        foreach ($items as $lvl)  
        {  
            $menu->add($lvl->title, $lvl->url, $this->build($lvl));  
        }  

        return $menu;  
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM