Pages

Thursday, January 3, 2013

N level Category Tree using php and mysql - [resolved]

First Method

function get_categories($parent = 0)
{
    $html = '<ul>';
    $query = mysql_query("SELECT * FROM `categories` WHERE `category_parent` = '$parent'");
    while($row = mysql_fetch_assoc($query))
    {
        $current_id = $row['category_id'];
        $html .= '<li>' . $row['category_name'];
        $has_sub = NULL;
        $has_sub = mysql_num_rows(mysql_query("SELECT COUNT(`category_parent`) FROM `categories` WHERE `category_parent` = '$current_id'"));
        if($has_sub)
        {
            $html .= get_categories($current_id);
        }
        $html .= '</li>';
    }
    $html .= '</ul>';
    return $html;
}

print get_categories();



Second Method


function generate_menu($category_parent, $menu_array=Array(), $level = 0, $first=0)
{
    $has_childs = false;

    if (empty($menu_array)) {

        $rs = mysql_query("SELECT category_id, category_parent, category_name FROM categories");

        while ( $row = mysql_fetch_assoc($rs) )
        {
                $menu_array[$row['category_id']] = array('category_name' => $row['category_name'],'category_parent' => $row['category_parent']);
        }       
    }

    foreach ($menu_array as $key => $value)
    {
        if ($value['category_parent'] == $category_parent)
        {  
            //if this is the first child print '<ul>'          
            if ($has_childs === false) {
                    //don't print '<ul>' multiple times            
                    $has_childs = true;
                    if ($first == 0){
                        echo "<ul category_id=\"nav\">\n";
                        $first = 1;
                    } else {
                        echo "\n<ul>\n";
                    }
            }
            $pad = str_repeat('&#8211; ', $level);
            echo "<li><a href=''>" . $value['category_name'] . "</a>";
            generate_menu($key, $menu_array, $level + 1, $first);
            //call function again to generate nested list for subcategories belonging to this category
            echo "</li>\n";
        }
    }
    if ($has_childs === true) echo "</ul>\n";
}
print generate_menu(0);

1 comment:

himanshu pandey said...

thanks i am working on this problem for last 3 days. thanks.