Crazy Coder
Crazy Coder

Reputation: 38

Codeigniter categories and sub categories function and pass to smarty variable

This is my codeigniter code for categories and sub categories when i echo the results outside the first foreach or pass results to smarty it only outputs last rows with last main id. But echo within the first foreach before closing } returns all results.

function getAllCats(){
    $this->load->model('mHtml', 'mnMod');
    $main_cat = $this->mnMod->getncats();
    $all_cat = '';
    foreach($main_cat as $mcat){
        $all_cat = '<li><h3><a href="{base_url()}'.$mcat->cname.'">'.$mcat->cname.'</a></h3>';
        $sub_cat = $this->mnMod->getscats($mcat->categoryid);
            foreach($sub_cat as $scat){
                $all_cat .= '<a href="{base_url()}'.$scat->cname.'">'.$scat->cname.'</a><br />';
                }
        $all_cat .= '</li>';
    }
  //  echo $all_cat; die;
    $this->smarty->assign("nav", $all_cat);
}

Results returned with mymethod.

Power Inverters

Off Grid Pure Sine Wave

Grid Tie String

Micro Grid Tie

Results i want to achieve and pass to smarty variable

Solar Panels

Monocrystalline

Polycrystalline

Flexible Solar

Charge Controllers

PWM

MPPT Technology

Power Inverters

Off Grid Pure Sine Wave

Grid Tie String

Micro Grid Tie

Upvotes: 1

Views: 118

Answers (2)

Ahmad Saad
Ahmad Saad

Reputation: 803

I have the same issue what i did i get all parent categories by one mysql query and in another i select all categories, simply i assign variables to smarty and foreach those results against each parent category.

$main_Categories = $this->model->all_categories();

$this->smarty->assign("main_Categories ", $main_Categories );

//On Smarty page

    {foreach $main_Categories  $cat}
     {if $cat->parentid = 'your parent id'} // parent id will be same for all main ids.
       {$cat->category_name}<br />
    {assign 'cat_id'  $cat->cat_id}
    {foreach $main_Categories  as $sub}
      {if $cat_id eq $sub->parent_id}
        {$sub->category_name}<br />
           {/if}
         {/foreach}
         {/if}
         {/foreach}

Upvotes: 3

OllyBarca
OllyBarca

Reputation: 1531

Loop through your $main_cats and assign sub_categories for each one. Good practice is to ensure $main_cats is an array before doing this.

Controller:

function getAllCats() {
    $this->load->model('mHtml', 'mnMod');
    $main_cats = $this->mnMod->getncats();
    if(is_array($main_cats))
    foreach($main_cats as &$mcat) {
        $mcat['subcat'] = $this->mnMod->getscats($mcat->categoryid);
    }

    $this->smarty->assign("cats", $main_cats);
}

View:

{if $cats}
     {foreach from=$cats item=cat}
        <li><h3><a href="{$cat.cname|base_url}">{$cat.cname}</a></h3>
        {foreach from=$cat item=sub_cat}
            <a href="{$sub_cat.cname|base_url}">{$sub_cat.cname}</a><br />
        {/foreach}
        </li>
     {/foreach}
{else}
    <p>No cats found</p>
{/if}

Upvotes: 1

Related Questions