Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array by using the same order of another one

I have 2 arrays containing starting poker hold'em hands.

One is composed of unordered values.

$array1 = array("65s","AA","J9s","AA","32s");
//the cards can be repeated here as you see there are 2 "AA"

and the other one that should be used as a model to order the first array:

$array_sorted = array("AA","KK","AKs"...);
//here the cards are not repeated

I'd like to re-order $array1 with the sort used in $array_sorted,

it should return an array like:

$array1 = array("AA","AA","J9s","65s","32s");

I have completely no idea on how to accomplish this. Maybe by using some "user defined sorting method"? Really don't know.

like image 949
Giorgio Avatar asked Jan 16 '12 19:01

Giorgio


1 Answers

You're right, and usort is the "user-defined sorting method" you're looking for. Something like this ought to work for you:

PHP >= 5.3

// Firstly this will be faster if the hands are the keys in the array instead
// of the values so we'll flip them with array_flip.
$array_sorted = array_flip( array( 'AA', 'KK', 'AKs', /* ... */ ) );
// => array( 'AA' => 0, 'KK' => 1, 'AKs' => 2, ... )

// your hands
$array1 = array( '65s', 'AA', 'J9s', 'AA', '32s' );

$array1_sorted = usort(
  $array1,

  // The comparison function 
  function($a, $b) {
    // If $a is AA and $b is J9s then
    // $array_sorted[ 'AA' ] - $array_sorted[ 'J9s' ]
    // will evaluate to a negative number, telling PHP that $a (AA)
    // is "smaller" than $b (J9s) and so goes first.
    return $array_sorted[ $a ] - $array_sorted[ $b ];
  }
);

PHP < 5.3

function sorting_function($a, $b){
  $array_sorted = array_flip( array( 'AA', 'KK', 'AKs', /* ... */ ) );

  return $array_sorted[ $a ] - $array_sorted[ $b ];
}

$array1 = array( '65s', 'AA', 'J9s', 'AA', '32s' );

$array1_sorted = usort( $array1, 'sorting_function' );
like image 106
Jordan Running Avatar answered Nov 09 '22 22:11

Jordan Running