我們在學習PHP時候,我們可能為PHP的多維數組排序的問題感到困惑,文章這裡就詳細的給大家介紹一下PHP多維數組排序的原理。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);?>
- 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
- )
- )