Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

php - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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' );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...