PHP允许在多维数组上执行一些比较复杂的排序——例如,首先对一个嵌套数组使用一个普通的关键字进行排序,然后再根据另一个关键字进行排序。这与使用SQL的ORDER BY语句对多个字段进行排序非常相似。为了能更好的明白它是如何工作的,请仔细看例子:
<?php $data = array(array("id" => 1, "name" => "Boney M", "rating" => 3), array("id" => 2, "name" => "Take That", "rating" => 1), array("id" => 3, "name" => "The Killers", "rating" => 4), array("id" => 4, "name" => "Lusain", "rating" => 3), ); foreach ($data as $key => $value) { $name[$key] = $value['name']; $rating[$key] = $value['rating']; } array_multisort($rating, $name, $data); print_r($data);?>
根据 rating 升序排序 结果:
Array ([0] => Array ( [id] => 2 [name] => Take That [rating] => 1 ) [1] => Array ( [id] => 1 [name] => Boney M [rating] => 3 ) [2] => Array ( [id] => 4 [name] => Lusain [rating] => 3 ) [3] => Array ( [id] => 3 [name] => The Killers [rating] => 4 ) )
array_multisort()函数是PHP中最有用的函数之一,它有非常广泛的应用范围。另外,就如你在例子中所看到的,它能对多个不相关的数组进行排序,也可以使用其中的一个元素作为下次排序的基础,还可以对数据库结果集进行排序。