以下の配列を考える。
1 2 3 4 5 6 7 |
$a[] = array('id' => 3, 'name' => 'aaa', 'date' => 12345); $a[] = array('id' => 5, 'name' => 'bbb', 'date' => 2345); $a[] = array('id' => 6, 'name' => 'ccc', 'date' => 332345); $a[] = array('id' => 1, 'name' => 'ddd', 'date' => 512345); $a[] = array('id' => 32, 'name' => 'eee', 'date' => 122345); print_r($a); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
Array ( [0] => Array ( [id] => 3 [name] => aaa [date] => 12345 ) [1] => Array ( [id] => 5 [name] => bbb [date] => 2345 ) [2] => Array ( [id] => 6 [name] => ccc [date] => 332345 ) [3] => Array ( [id] => 1 [name] => ddd [date] => 512345 ) [4] => Array ( [id] => 32 [name] => eee [date] => 122345 ) ) |
この配列をdateの値でソートしたい場合は以下のようにする。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$a[] = array('id' => 3, 'name' => 'aaa', 'date' => 12345); $a[] = array('id' => 5, 'name' => 'bbb', 'date' => 2345); $a[] = array('id' => 6, 'name' => 'ccc', 'date' => 332345); $a[] = array('id' => 1, 'name' => 'ddd', 'date' => 512345); $a[] = array('id' => 32, 'name' => 'eee', 'date' => 122345); print_r($a); function mycmp($lhv, $rhv) { return $lhv['date'] - $rhv['date']; } usort($a, 'mycmp'); print_r($a); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
Array ( [0] => Array ( [id] => 5 [name] => bbb [date] => 2345 ) [1] => Array ( [id] => 3 [name] => aaa [date] => 12345 ) [2] => Array ( [id] => 32 [name] => eee [date] => 122345 ) [3] => Array ( [id] => 6 [name] => ccc [date] => 332345 ) [4] => Array ( [id] => 1 [name] => ddd [date] => 512345 ) ) |
mycmpの2つの引数には配列の値が適当に渡される。内部でクイックソートなどを行って実際の比較の時にこの関数が呼ばれると思われる。この関数で、第一引数が第二引数よりも前に来るならマイナスを返し、同じなら0を返し、後ろに来るならプラスを返す。