我有一个包含北、东、南或西值的数组。
例如我得到一个数组,其中包含:
['south', 'west', 'north']
现在我想按自定义顺序对数组进行排序,例如:
north
,然后east
,然后south
,然后west
。
因此,在我的示例中,值应按以下顺序排列:
['north', 'south', 'west']
我怎样才能做到这一点?
array_intersect()
。它保留第一个数组的顺序。以正确的顺序给出所有基本方向的数组作为第一个参数,并将要排序的数组作为第二个参数。
$cardinals = array( 'north', 'east', 'south', 'west' );
$input = array( 'south', 'west', 'north' );
print_r( array_intersect( $cardinals, $input ) );
你可以按照这个思路做一些事情(我相信这也是塞缪尔·洛佩兹在评论中所建议的):
$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
为一(除非您在中间添加一些内容)等。