title: Building a Parent child Category Codeigniter
body: <p>I have managed to create parent and child categories, I am using One table for categories, with fields cat_id, cat_name_cat_parent_id. So its all working. But I want to display these categories inside my product adding page, and It should be displayed as a select box option group values with Parent Category as a title disabled and child categories underneath. as below</p>
  
  <pre><code>&lt;select&gt;
    &lt;optgroup label="Parent Category 1"&gt;
      &lt;option value="1"&gt;sub cat 1&lt;/option&gt;
      &lt;option value="2"&gt;sub cat 2&lt;/option&gt;
    &lt;/optgroup&gt;
    &lt;optgroup label="Parent Category 2"&gt;
      &lt;option value="mercedes"&gt;sub cat 1&lt;/option&gt;
      &lt;option value="audi"&gt;sub cat 2&lt;/option&gt;
    &lt;/optgroup&gt;
  &lt;/select&gt;
  </code></pre>
  
  <p>by using my cat_model function I can fetch all the categories and their parent category id, but how to group it as I mentioned above and pass to select group</p>
  
  <p>In my controller I am using this function to get all categoies:</p>
  
  <pre><code>$this-&gt;data['product_categories'] = $this-&gt;category_m-&gt;get();
  </code></pre>
  
  <p><strong>UPDAT:::</strong>
  I have managed to get this by creating two functions to get parent and child seperately, like this::</p>
  
  <pre><code>public function getAllParents();
  public function getAllChild($id)
  </code></pre>
  
  <p>and using the second function inside the loop of fist functions result. Is this the proper way to do this, or any another proper ways. I my view file I am using like this::</p>
  
  <pre><code> &lt;optgroup label="&lt;?php echo $parent-&gt;category_name; ?&gt;"&gt;
        &lt;?php $children = $controller-&gt;getAllChild($parent-&gt;category_id);
             foreach ($children as $child) { ?&gt;
                     &lt;option value="&lt;?php echo $child-&gt;category_id ;?&gt;" 
             &lt;?=set_select('product_category', $child-&gt;category_id); ?&gt;&gt;&lt;?php echo $child-&gt;category_name; ?&gt;
  &lt;/option&gt;
              &lt;?php } ?&gt;
        &lt;/optgroup&gt;
  </code></pre>