使用PHP中的数组按名称对类别进行排序

时间:2012-04-01 09:43:24

标签: php arrays sorting alphabetical

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 

这是我的类别列表,由此代码输出:

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

现在,$ categories子类别名称被正确定义,之前在代码中通过:

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'];

    }
}

我希望输出按字母顺序输出,所以从上面的例子中,它应该输出如下内容:

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

我尝试了简单的sort(),asort(),但它们不适合我。我怎样才能做到这一点?谢谢你前进

1 个答案:

答案 0 :(得分:0)

尝试usort,因为您可以定义自己的比较器(http://at2.php.net/manual/de/function.usort.php)

示例:

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

usort($categories, "cmpCategories");