使用usort对数组进行排序

时间:2011-12-28 18:00:31

标签: php arrays sorting usort

我有一个包含北,东,南或西值的数组。

例如,我得到了一个数组,其数值按此顺序排列:南,西和北。

现在我想将数组分类为北,东,南和西。

所以在我的例子中,值应按此顺序排列:北,南,西。

我该怎么做?

谢谢!

2 个答案:

答案 0 :(得分:6)

您也可以使用array_intersect()。它保留了第一个数组的顺序。以正确的顺序给出所有基本方向的数组作为第一个参数,并将数组排序为第二个。

$cardinals = array( 'north', 'east', 'south', 'west' );
$input = array( 'south', 'west', 'north' );

print_r( array_intersect( $cardinals, $input ) );

答案 1 :(得分:0)

你可以做一些事情(我相信这是Samuel Lopez在评论中也提出的建议):

$arr = array ('north', 'west', 'south', 'east', );

function compass_sort ($a, $b)
{
        $cmptable = array_flip (array (
                'north',
                /* you might want to add 'northeast' here*/
                'east',
                /* and 'southeast' here */
                'south',
                'west',
        ));

        $v1 = trim (mb_strtolower ($a));
        $v2 = trim (mb_strtolower ($b));

        if ( ! isset ($cmptable[$v1])
           || ! isset ($cmptable[$v2]))
        {
                /* error, no such direction */
        }

        return $cmptable[$v1] > $cmptable[$v2];
}

usort ($arr, 'compass_sort');

这会为每个方向指定一个数字并对该数字进行排序,north将被指定为零,east一个(除非您在其间添加内容)等。