php sorting an array by predefined order

arrays, php, sorting

Solution

This method will sort an array using a pre-defined order of keys using `uksort`

$desiredIndexOrder = array(4 => 1, 0 => 2, 1 => 3, 2 => 4, 3 => 5);

uksort($inputArray, function($a, $b) use ($desiredIndexOrder) {
    return $desiredIndexOrder[$a] > $desiredIndexOrder[$b] ? -1 : 1;
});

Notice the `$desiredIndexOrder` array is in `index => desired sort position` format. If you don't want to put your array in that format, you can have it built for you using this:

$desiredIndexOrder = array();

foreach ($desiredKeyOrder as $position=>$key) {
    $desiredIndexOrder[$key] = $position + 1;
}

Where `$desiredKeyOrder` is the array order of your keys: `array(4, 0, 1, 2, 3)`

Problem

I'm struggling trying to sort an array via the normal functions, i'm sure this needs a custom comparison function but none the less will chuck this out there. I have an array with 5 elements inside it. I would like the array to sort itself like so, arsort came close but not quite: 4,0,1,2,3 Just to clarify, the position of the array like: $array[0]; I haven't actually looked at array comparison functions before, so a push in the right direction would be most helpful to solve this! Thanks, Adam

Original source