Jordy
Jordy

Reputation: 4809

Sort flat array with a known set of possible values in a custom order

I have an array that contain the values north, east, south or west.

For example I got an array containing:

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

Now I would like to sort the array in a custom order like: north, then east, then south, then west.

So in my example the values should be in this order:

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

How can I do that?

Upvotes: 1

Views: 194

Answers (2)

zrvan
zrvan

Reputation: 7743

You could do something along the lines of this (I believe it's what Samuel Lopez is also suggesting in the comments):

$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');

This assigns a number to each direction and sorts on that number, north will be assigned zero, east one (unless you add something in between) etc.

Upvotes: 0

JJJ
JJJ

Reputation: 33163

You could also use array_intersect(). It preserves the order of the first array. Give an array of all cardinal directions in the correct order as the first parameter and the array to sort as the second.

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

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

Upvotes: 6

Related Questions