Smarty PHP category tree using php function

Recently i was trying to create category tree using php function and assign function into variable.

You need to have id_parent  or parent category id to achieve what i did in following code.

PHP Function:

 

function getCategoriesTree($id_shop,$id_category) { $sql = "SELECT "._DB_PREFIX_."category.id_category, "._DB_PREFIX_."category.id_parent,"._DB_PREFIX_."category.level_depth,"._DB_PREFIX_."category.is_root_category, "._DB_PREFIX_."category_lang.id_shop,"._DB_PREFIX_."category_lang.id_lang,"._DB_PREFIX_."category_lang.name,"._DB_PREFIX_."category_lang.description, "._DB_PREFIX_."category_lang.link_rewrite, "._DB_PREFIX_."category_lang.meta_title, "._DB_PREFIX_."category_lang.meta_keywords,"._DB_PREFIX_."category_lang.meta_description FROM "._DB_PREFIX_."category LEFT JOIN "._DB_PREFIX_."category_lang ON "._DB_PREFIX_."category.id_category = "._DB_PREFIX_."category_lang.id_category WHERE "._DB_PREFIX_."category.id_shop_default='$id_shop' AND "._DB_PREFIX_."category_lang.id_shop='$id_shop' AND "._DB_PREFIX_."category.id_parent = '$id_category'"; $results = Db::getInstance()->ExecuteS($sql); $html = ""; foreach($results as $row){ $html .= "
    "; $html .= "
  • "; $html .= $row['name']; $html .= getCategoriesTree($id_shop,$row['id_category']); $html .= "
  • "; $html .= "
"; } if(isset($html)) return $html; }

PHP->TPL Assignment:

$smarty->assign("category_tree",getCategoriesTree($id_shop,0));

PHP Smarty TPL Code:

{foreach $category_tree as $categories} {$categories} {/foreach}

This will result as Following Tree:
  • Root
    • Home
      • Women
        • Tops
          • T-shirts
            • Test
          • Tops
          • Blouses
        • Dresses
          • Casual Dresses
          • Evening Dresses
          • Summer Dresses
            • Dresses