Search code examples
phparrayssortingalphabetical

Sort categories by name with array in PHP


Armstuff > xxxxx 
Uncategorized
Biler > test 
HOVED > SUB 
Computere > Software 
Smykker 
Computere > Komponenter > RAM 
sss > bbb > kkk 
Computere > Komponenter > Harddiske 
gg 
Computere > Gadgets 
Biler > Ekstraudstyr 
sss > ddd 

This is a list of my categories, outputted by this code:

<?php
foreach($categories as $category)
{
    echo $category['name'] . " <br />";
}
?>

Now the $categories sub category names gets defined correctly, previously in the code by:

foreach($categories as &$category)
{

    $parent = $category['parent'];
    while($parent > 0)
    {
        $parent_row = $db->select('name', 'paraent')->from('categories')->where('id', '=', $parent)->execute()->as_array();
        $parent_row = $parent_row[0];
        $category['name'] = $parent_row['name'] . " > {$category['name']}";
        $parent = $parent_row['parent'];

    }
}

I wish the output to output alphabetic, so from the above example, it should output something like :

Armstuff > xxxxx
Biler > test
Biler > Ekstraudstyr
Computere > Gadgets
Computere > Komponenter > Harddiske
Computere > Komponenter > RAM
Computere > Software
gg
HOVED > SUB
Smykker
sss > bbb > kkk
sss > ddd
Uncategorized

I tried the simply sort(), asort() but they wouldnt work out for me. How can i do this? Thanks in forward


Solution

  • Try usort because you can define your own comparer (http://at2.php.net/manual/de/function.usort.php)

    Example:

    function cmpCategories($a, $b) {
        if ($a["name"] == $b["name"]) {
            return 0;
        }
        return ($a["name"] < $b["name"]) ? -1 : 1;
    }
    
    usort($categories, "cmpCategories");