I have categories and subcategories in my web project. I’m new to smarty. Normally I use below code to build a category tree. Main categories are defined by parent id = 0 and all the subcategories have main category id as their parent id
$sql = "SELECT * FROM categories ORDER BY category";
$res = $mysqli->query($sql);
while ($row = mysqli_fetch_assoc($res)) {
$parent = intval($row['parent_id']);
if (!isset($categories[$parent])) {
$categories[$parent] = array();
}
$categories[$parent][] = $row;
}
function build_categories($parent, $categories) {
if (isset($categories[$parent]) && count($categories[$parent])) {
foreach ($categories[$parent] as $category) {
$cat_name = $category['category'];
$cat_link = preg_replace("![^a-z0-9]+!i", "-", $cat_name);
$cat_link = urlencode($cat_link);
$cat_link = strtolower($cat_link);
if($category['parent_id']==0){
echo '<li><a href="category-'.$category['cat_id'].'-'.$cat_link.'">' .$category['category'].'</a>';
}else{
echo '<li><a href="subcategory-'.$category['cat_id'].'-'.$cat_link.'"><span class="fa fa-angle-double-right"></span> '.$category['category'].'</a>';
}
echo build_categories($category['cat_id'], $categories);
echo '</li>';
}
}
}
//output category tree
build_categories(0, $categories);
//table structure
cat_id | category | parent_id
1 | cat 1 | 0
1 | cat 2 | 0
1 | cat 3 | 1
1 | cat 4 | 2
1 | cat 5 | 1
please note that above code work just dont work when i assign it smarty variable.
But i cannot seems to get it to work with Smarty. appricate your help.