利用PHP的usort函数对多维数组按照指定的顺序进行排序:
例如:
public function ceshi() { $arr1 = array( array('id' => 1, 'name' => 'yhp'), array('id' => 2, 'name' => 'yhp2'), array('id' => 3, 'name' => 'yhp3'), array('id' => 4, 'name' => 'yhp4'), array('id' => 5, 'name' => 'yhp5'), array('id' => 6, 'name' => 'yhp6'), array('id' => 7, 'name' => 'yhp7'), array('id' => 8, 'name' => 'yhp8'), array('id' => 9, 'name' => 'yhp9'), array('id' => 10,'name' => 'yhp10'), ); echo "排序前的数组:<pre>"; print_r($arr1); echo "</pre>"; usort($arr1, array($this, "compare")); echo "排序后的数组:<pre>"; print_r($arr1); echo "</pre>"; } public function compare($a, $b) { $arr2 = array(6,8,7,9,3,2,4,1,5,10,11,12); return (array_search($a['id'], $arr2) < array_search($b['id'], $arr2)) ? -1 : 1; }
排序后的数组:
Array ( [0] => Array ( [id] => 6 [name] => yhp6 ) [1] => Array ( [id] => 8 [name] => yhp8 ) [2] => Array ( [id] => 7 [name] => yhp7 ) [3] => Array ( [id] => 9 [name] => yhp9 ) [4] => Array ( [id] => 3 [name] => yhp3 ) [5] => Array ( [id] => 2 [name] => yhp2 ) [6] => Array ( [id] => 4 [name] => yhp4 ) [7] => Array ( [id] => 1 [name] => yhp ) [8] => Array ( [id] => 5 [name] => yhp5 ) [9] => Array ( [id] => 10 [name] => yhp10 ) )