<?php //創建一個二維陣列,希望按照 order 排序 $array[] = [ 'id' => 2, 'name' => 'ccc', 'order' => 3, ]; $array[] = [ 'id' => 0, 'name' => 'aaa', 'order' => 0, ]; $array[] = [ 'id' => 1, 'name' => 'bbb', 'order' => 1, ]; usort($array, function($a, $b) { return $a['order'] - $b['order']; }); echo '排序後的結果'; echo "<pre>".print_r($array, 1)."</pre>"; ?>
排序後的結果
Array ( [0] => Array ( [id] => 0 [name] => aaa [order] => 0 ) [1] => Array ( [id] => 1 [name] => bbb [order] => 1 ) [2] => Array ( [id] => 2 [name] => ccc [order] => 3 ) )
usort 運作原理的說明,可以參考這篇
沒有留言:
張貼留言