php array_multisort對數據庫結果多個字段進行排序
$data 數組中的每個單元表示一個表中的一行。這是典型的數據庫記錄的數據集合。
例子中的數據如下:
volume | edition -------+-------- 67 | 2 86 | 1 85 | 6 98 | 2 86 | 6 67 | 7
數據全都存放在名為 data 的數組中。這通常是通過循環從數據庫取得的結果,例如 mysql_fetch_assoc()。
<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
?>
本例中將把 volume 降序排列,把 edition 升序排列。
現在有了包含有行的數組,但是 array_multisort() 需要一個包含列的數組,因此用以下代碼來取得列,然后排序。
<?php
// 取得列的列表
foreach ($data as $key => $row) {
$volume[$key] = $row['volume'];
$edition[$key] = $row['edition'];
}
// 將數據根據 volume 降序排列,根據 edition 升序排列
// 把 $data 作為最后一個參數,以通用鍵排序
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>
數據集合現在排好序了,結果如下:
volume | edition -------+-------- 98 | 2 86 | 1 86 | 6 85 | 6 67 | 2 67 | 7
====================================================
實例2:
//有優惠活動優先 + 上架時間 最新時間的在最上面
//根據商品id取出來然后在用數組排序array_multisort
foreach ($goods as $key => $row) {
$start_time[$key] = $row['goods_listing_start_time'];
$is_activity[$key] = $row['is_activity'];
}
//SORT_ASC SORT_DESC
array_multisort($is_activity,SORT_DESC,$start_time, SORT_DESC, $goods);