Here is a way to implement this using pure PHP with a recursive function ...
First we define an array of categories:
$categories = [ ['id' => 1, 'name' => 'TV & Home Theather'], ['id' => 2, 'name' => 'Tablets & E-Readers'], ['id' => 3, 'name' => 'Computers', 'children' => [ ['id' => 4, 'name' => 'Laptops', 'children' => [ ['id' => 5, 'name' => 'PC Laptops'], ['id' => 6, 'name' => 'Macbooks (Air/Pro)'] ]], ['id' => 7, 'name' => 'Desktops'], ['id' => 8, 'name' => 'Monitors'] ]], ['id' => 9, 'name' => 'Cell Phones'] ];
Next, we define a recursive function that will pass category names to parents:
function printCats($categories, $parent = NULL) { while ($category = array_shift($categories)) { $catName = ($parent ? $parent.' >> ' : '').$category['name']; print("<option value='{$category['id']}'>{$catName}</option>\n"); if (isset($category['children'])) printCats($category['children'], $catName); } }
And finally, a call passing a category tree:
printCats($categories);
Output:
<option value='1'>TV & Home Theather</option> <option value='2'>Tablets & E-Readers</option> <option value='3'>Computers</option> <option value='4'>Computers >> Laptops</option> <option value='5'>Computers >> Laptops >> PC Laptops</option> <option value='6'>Computers >> Laptops >> Macbooks (Air/Pro)</option> <option value='7'>Computers >> Desktops</option> <option value='8'>Computers >> Monitors</option> <option value='9'>Cell Phones</option>
source share