aliasgar vanak aliasgar vanak - 3 months ago 8
MySQL Question

Display Category and Subcategory In nested format

I am working on category and sub category section where I want to display all the subcategory under their respective category.

It is something similar like Wordpress Category Sub Category display. I want to run this thing in Codeigniter.

Below is my array

Array
(
[0] => Array
(
[name] => 1 Category
[children] => Array
(
[0] => Array
(
[name] => 1 Sub Category
)

[1] => Array
(
[name] => 2nd 1 Sub Category
)

)

)

[1] => Array
(
[name] => 6 Category
[children] => Array
(
[0] => Array
(
[name] => 6 Sub Category
[children] => Array
(
[0] => Array
(
[name] => 2 Sub Category
[children] => Array
(
[0] => Array
(
[name] => 7 Sub Category
)

)

)

)

)

)

)

)


And my desire out is:

1 Category
- 1 Sub Category
- 2nd 1 Sub Category
6 Category
- 6 Sub Category
- 2 Sub Category
- 7 Sub Category


Another Desired Output :

<select>
<option>1 Category</option>
<option>- 1 Sub Category</option>
<option>- 2nd 1 Sub Category</option>
<option>6 Category</option>
<option>- 6 Sub Category</option>
<option>- - 2 Sub Category</option>
<option>- - - 7 Sub Category</option>
</select>


I hope i am clear with my question and desired output.

Answer

I have created a function which returns ul,li result for your input.. Try this..

get_category($array);

function get_category($array) {
    echo '<ul>';
    foreach($array as $category) {
        echo '<li>';
        echo $category['name'];
        if(isset($category['children'])) {
            get_category($category['children']);
        }
        echo '</li>';
    }
    echo '</ul>';
}

Update for Select output

echo '<select>';
get_category($array);
echo '</select>';

function get_category($array, $prefix = '') {
    foreach($array as $category) {
        echo '<option>';
        echo $prefix . $category['name'];
        echo '</option>';
        if(isset($category['children'])) {
            get_category($category['children'], $prefix.'- ');
        }
    }
}
Comments