Welcome Guest, Not a member yet? Register   Sign In
Get recursive menu from database
#5

[eluser]Dam1an[/eluser]
Ok, here's some quick code I've mocked up

Code:
<?php
class Test extends Controller {
    function index() {
        $menu = Test::create_nested_menu();
        
        print_r($menu);
    }
    
    function create_nested_menu($parent = 0) {
        $items = array();
        
        $this->db->where('parent', $parent);
        $query = $this->db->get('menu_items');
        $results = $query->result();
        
        foreach($results as $result) {
            $child_array = Test::create_nested_menu($result->id);
            if(sizeof($child_array) == 0) {
                array_push($items, $result->label);
            } else {
                array_push($items, array($result->label, $child_array));
            }
        }
        
        return $items;
    }
}
?>

and with the array in your example, it would generate the following array
Code:
Array (
    [0] => Label 1
    [1] => Array (
        [0] => Label 2
        [1] => Array (
            [0] => Array (
                [0] => Label 2.1
                [1] => Array (
                    [0] => Label 2.1.1
                )
            )
            [1] => Label 2.2
        )
    )
    [2] => Label 3
    [3] => Label 4
)

You'll obviously want to move the function into a helper, but you get the idea (hopefully)
If not, I'll explain it in detail Smile


Messages In This Thread
Get recursive menu from database - by El Forum - 04-21-2009, 03:56 PM
Get recursive menu from database - by El Forum - 04-21-2009, 04:09 PM
Get recursive menu from database - by El Forum - 04-21-2009, 04:22 PM
Get recursive menu from database - by El Forum - 04-22-2009, 12:52 AM
Get recursive menu from database - by El Forum - 04-22-2009, 07:32 AM
Get recursive menu from database - by El Forum - 04-26-2009, 07:58 AM
Get recursive menu from database - by El Forum - 04-26-2009, 12:43 PM
Get recursive menu from database - by El Forum - 04-26-2009, 01:38 PM
Get recursive menu from database - by El Forum - 04-26-2009, 03:09 PM
Get recursive menu from database - by El Forum - 04-26-2009, 03:21 PM
Get recursive menu from database - by El Forum - 04-26-2009, 04:05 PM
Get recursive menu from database - by El Forum - 10-25-2010, 04:23 AM



Theme © iAndrew 2016 - Forum software by © MyBB