[Solved] Sorting the array using keys [closed]


Two things are important here. You need to preserve the key to value relationship. That implies that you use array sorting functions like uasort() instead of usort(). The next thing is, that you have to use a user-defined sorting function, which expresses your sorting algo. It describes how you want to sort your routes.

It’s also possible to sort by keys: then array_flip() is your friend.

You might use this for starting:

<?php

$routes=[
    '/about'                     =>['ALL','static'],
    '/[:name]/[:name]/[:name]'   =>['ALL','dynamic','blog'],
    '/news'                      =>['ALL','static','news'],
];

function sortShortestRoute($a, $b)
{
    return (count($a) < count($b)) ? -1 : 1;
}

function sortStaticBeforeDynamic($a, $b)
{
    if($a[1] === 'static' && $b[1] === 'static') {
        return 1;
    }

    if($a[1] === 'dynamic' && $b[1] === 'dynamic') {
        return -1;
    }

    if ($a[1] === $b[1]) {
        return 0;
    }
}

// first sort
uasort($routes, 'sortStaticBeforeDynamic');

var_dump($routes);

// second sort
uasort($routes, 'sortShortestRoute');

var_dump($routes);

solved Sorting the array using keys [closed]