Skip to content
PHP Logo

How can an array be sorted in PHP to display nested categories as described in the example?

To display nested categories in a sorted manner, we can use a recursive function to sort the array based on the parent-child relationship of the categories. We can achieve this by first sorting the array by the parent_id and then recursively sorting the children of each category. This will ensure that the nested categories are displayed in the correct order.

php
function sortCategories($categories, $parent_id = 0) {
    $sortedCategories = array();

    foreach ($categories as $category) {
        if ($category['parent_id'] == $parent_id) {
            $sortedCategories[] = $category;
            $sortedCategories = array_merge($sortedCategories, sortCategories($categories, $category['id']));
        }
    }

    return $sortedCategories;
}

// Assuming $categories is the array of nested categories
$sortedCategories = sortCategories($categories);

foreach ($sortedCategories as $category) {
    echo $category['name'] . "\n";
}