usort
usort — ユーザー定義の比較関数を使用して、配列を値でソートする
usort ( array &$array , callable $value_compare_func ) : bool
使い方の例
rsort.php
$data = ['Thomas Jefferson','Andrew Jackson','John Adams','George Washington','James Monroe'];
usort($data,'usortPre');
print_r($data); //Array ( [0] => George Washington [1] => John Adams [2] => Thomas Jefferson [3] => James Monroe [4] => Andrew Jackson )
function usortPre($a,$b){
$presidents = ['George Washington','John Adams','Thomas Jefferson','James Madison','James Monroe','John Quincy Adams','Andrew Jackson','Martin Van Buren'];
return array_search($a,$presidents) <=> array_search($b,$presidents);
}
usortPreの返り値によって、$dataを並び替える
$a | $b | array_search($a,$presidents) | array_search($a,$presidents) | array_search($a,$presidents) <=> array_search($b,$presidents) |
---|---|---|---|---|
Thomas Jefferson | Andrew Jackson | 2 | 6 | -1 |
Andrew Jackson | John Adams | 6 | 1 | 1 |
Thomas Jefferson | John Adams | 2 | 1 | 1 |
Andrew Jackson | George Washington | 6 | 0 | 1 |
…省略 |
<=> : 左辺が大きいと、1を返す。右辺が大きいと、-1を返す。等しいと0を返す
帰ってきた値(0,-1,1)をもとに、usortでは
0の場合は並び替えなし。
1の場合は_$a_の順番を_$b_より繰り下げる.
-1の場合は_$a_の順番を_$b_より繰りあげる.