Search code examples
phparrayssortingphp-7.3

Sort array based on user-defined order of index


I would like to restructure the array (not traditional sort), based on providing the wanted index order, e.g. [1,7,4]. Below just sorts ascending order based on value.

wanted result:

Array
(
    [1] => c
    [4] => b
    [7] => a
)

My code:

$array = [];

$array[4] = "b";
$array[1] = "c";
$array[7] = "a";

print_r($array);

echo "\n\n" . "Sort ascending..." . "\n\n";
asort($array);
print_r($array);

Result:

Array
(
    [4] => b
    [1] => c
    [7] => a
)


Sort ascending...

Array
(
    [7] => a
    [4] => b
    [1] => c
)

Solution

  • So what you need to do is build a custom function so you can pass in the sort keys for your custom ordering. This will take your keys and then pull each key from the array and build a new array with the correct order as desired.

    $array = [];
    
    $array[4] = "b";
    $array[1] = "c";
    $array[7] = "a";
    
    function sortByKeyOrder(array $sortOrderKeys, array $arrayToSort){
       $output = [];
       foreach($sortOrderKeys as $index){
         if(isset($arrayToSort[$index])){
             $output[$index] = $arrayToSort[$index];
         }
       }
    
      return $output;
    }
    
    //usage 
    sortByKeyOrder([1, 4, 7], $array);