Here is an example of using uksort with closure, it should be more efficient on a large array, I think, but I havenβt done any benchmark, so ... it's hard to really check without a test.
$a = array( 12 => 'blah' ,36 => 'foo' ,58 => 'blah' ,60 => 'blah' ,72 => 'blah' ,90 => 'bar' ); $b = array( 36 => 'foo data' ,90 => 'bar data' ,12 => 'blah data' ); $keysPosition = array_flip(array_keys($b)); uksort($a,function($a,$b) use ($keysPosition){ if(isset($keysPosition[$a],$keysPosition[$b])){ return $keysPosition[$a]>$keysPosition[$b]?1:-1; }else if( isset($keysPosition[$a]) ){ return -1; }else if( isset($keysPosition[$b]) ){ return 1; } return 0; }); print_r($a);
result:
Array ( [36] => foo [90] => bar [12] => blah [72] => blah [58] => blah [60] => blah )
If you cannot use closure (php <5.3), you can do something similar using global, but it doesn't get cleared at all.
malko
source share