使用一组已知的可能值按自定义顺序对平面数组进行排序

问题描述 投票:0回答:2

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

例如我得到一个数组,其中包含:

['south', 'west', 'north']

现在我想按自定义顺序对数组进行排序,例如:

north
,然后
east
,然后
south
,然后
west

因此,在我的示例中,值应按以下顺序排列:

['north', 'south', 'west']

我怎样才能做到这一点?

php arrays sorting usort custom-sort
2个回答
6
投票

您也可以使用

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

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

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

0
投票

你可以按照这个思路做一些事情(我相信这也是塞缪尔·洛佩兹在评论中所建议的):

$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
为一(除非您在中间添加一些内容)等。

© www.soinside.com 2019 - 2024. All rights reserved.