Welcome Guest, Not a member yet? Register   Sign In
Dynamic array for UL method in HTML helper
#2

[eluser]JoostV[/eluser]
Fetching from database in a loop is a dangerous manouvre. As your table grows, you could end up with hundreds of queries.

If your category list is no more than two levels deep, you can fetch all categories in a single query and loop through the results to create an array that will display nicely with ul():
Code:
// Fetch categories, no parents first
$categories = $this->db->order_by('Parent')->get('categories')->results_array();

// Create an array of links, to display with ul()
if (is_array($categories) && count($categories)) {
    
    // Turn you category array into an assoc array, with ID being the key
    // We need this to be able to retrieve the proper parent anchors, later on
    $tmp_array = array();
    foreach ($categories as $category) {
        $key = current($category);
        $tmp_array[$key] = $category;
    }
    
    // Construct an array of navigation links, ready to use with ul();
    $nav_array = array();
    foreach ($categories as $page) {
        
        // Set anchors
        $href = anchor('cat/' . $page['ID'], $page['Categoryname']);
        $parenthref = anchor('cat/' . $page['Parent'], $categories[$page['Parent']]['Categoryname']);
        
        if ($page['Parent'] == 0) {
            // This is a level 1 anchor
            $nav_array[$page['ID']] = $href;
        }
        else {
            // This is a level 2 anchor
            if (isset($nav_array[$page['Parent']])) {
                unset($nav_array[$page['Parent']]);
                $nav_array[$parenthref] = array();
            }
            $nav_array[$parenthref][$page['ID']] = $href;
        }
    }
}


Messages In This Thread
Dynamic array for UL method in HTML helper - by El Forum - 07-30-2011, 09:21 AM
Dynamic array for UL method in HTML helper - by El Forum - 07-30-2011, 03:55 PM
Dynamic array for UL method in HTML helper - by El Forum - 07-30-2011, 05:22 PM
Dynamic array for UL method in HTML helper - by El Forum - 07-31-2011, 02:57 AM
Dynamic array for UL method in HTML helper - by El Forum - 07-31-2011, 05:41 AM



Theme © iAndrew 2016 - Forum software by © MyBB