LoginSignup
1
0

More than 3 years have passed since last update.

「usort」自分のルールでソートする

Posted at

usort

PHP公式サイト

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より繰りあげる.

参考

【 php 】usort関数の使い方

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0