Sort an array by using the same order of another one

后端 未结 1 1775
执念已碎
执念已碎 2020-12-19 12:03

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

One is composed of unordered values.

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


        
1条回答
  •  时光说笑
    2020-12-19 12:13

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

    0 讨论(0)
提交回复
热议问题