對於Listing J示例為我們具體說明了PHP函數array_multisort()的工作方式:
- <?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);
- ?>
這裡,我們在$data數組中模擬了一個行和列數組。然後,我使用PHP函數array_multisort()對數據集合進行重排,首先是根據rating進行排序,然後,如果rating相等的話,再根據name排序。它的輸出結果如下:
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
)
)
PHP函數array_multisort()是PHP中最有用的函數之一,它有非常廣泛的應用范圍。另外,就如你在例子中所看到的,它能對多個不相關的數組進行排序,也可以使用其中的一個元素作為下次排序的基礎,還可以對數據庫結果集進行排序。