danieliser
1/7/2016 - 10:18 PM

PHP Sort array by user defined order pushing unknown keys to the end of the list.

PHP Sort array by user defined order pushing unknown keys to the end of the list.

<?php
function sort_array_using_array( $a, $b ) {
    $order = array(
            __( 'First', 'popup-maker' ),
            __( 'Second', 'popup-maker' ),
            __( 'Third', 'popup-maker' ),
    );

    $ai = in_array( $a, $order ) ? array_search ( $a, $order ) : count( $order ) + 1;
    $bi = in_array( $b, $order ) ? array_search ( $b, $order ) : count( $order ) + 1;

    if ( $ai == $bi ) {
        return 0;
    }

    // Compare their positions in line.
    return $ai > $bi ? 1 : -1;
}

$test = array(
  'Tenth' => 10,
  'Eighth' => 8,
  'First' => 1,
  'Fourth' => 4,
  'Second' => 2,
  'Fifth' => 5,
  'Third' => 3,
);
uksort( $test, 'sort_array_using_array' );
print( $test );
?>
Results:

[
  'First' => 1,
  'Second' => 2,
  'Third' => 3,
  'Tenth' => 10,
  'Eighth' => 8,
  'Fourth' => 4,
  'Fifth' => 5,
]