// get all categories
$categories = fetchCategories();
// format the categories for display
$categories = formatCategories($categories, $catId);
?>
<ul>
<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>">All Category</a></li>
<?php
foreach ($categories as $category) {
extract($category);
// now we have $cat_id, $cat_parent_id, $cat_name
function formatCategories($categories, $parentId)
{
// $navCat stores all children categories
// of $parentId
$navCat = array();
// expand only the categories with the same parent id
// all other remain compact
$ids = array();
foreach ($categories as $category) {
if ($category['cat_parent_id'] == $parentId) {
$navCat[] = $category;
}
// save the ids for later use
$ids[$category['cat_id']] = $category;
}
$tempParentId = $parentId;
// keep looping until we found the
// category where the parent id is 0
while ($tempParentId != 0) {
$parent = array($ids[$tempParentId]);
$currentId = $parent[0]['cat_id'];
// get all categories on the same level as the parent
$tempParentId = $ids[$tempParentId]['cat_parent_id'];
foreach ($categories as $category) {
// found one category on the same level as parent
// put in $parent if it's not already in it
if ($category['cat_parent_id'] == $tempParentId && !in_array($category, $parent)) {
$parent[] = $category;
}
}
// sort the category alphabetically
array_multisort($parent);
We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.
PHP menu retrieve parent/child
in PHP Coding Help
Posted