我有排序方向的問題。我嘗試用方向對多維數組進行排序。我不能直接使用array_multisort()
,因爲我不知道會有多少參數。我使用call_user_func_array('array_multisort', $params);
它可以工作,但我無法設置排序方向(SORT_ASC,SORT_DESC
)。我如何設置call_user_func_array('array_multisort', $params);
的排序方向? 這裏是我的代碼,你可以嘗試call_user_func_array array_multisort
function get_fields($data, $order_by) {
$order_row = preg_split("/[\s,]+/", $order_by);
for ($i=0;$i<count($order_row);$i++) {
foreach ($data as $key => $row) {
$tmp[$i][$key] = $row[$order_row[$i]];
}
}
return $tmp;
}
function ordering($data, $order_by) {
$tmp = get_fields($data, $order_by);
$params = array();
foreach($tmp as &$t){
$params[] = &$t;
}
$params[1] = array("SORT_DESC","SORT_DESC","SORT_DESC","SORT_DESC"); // like that no warning but no sorting
$params[] = &$data;
call_user_func_array('array_multisort', $params);
return array_pop($params);
}
$data = array (
array('id' => 1,'name' => 'Barack','city' => 9),
array('id' => 7,'name' => 'boris','city' => 2),
array('id' => 3,'name' => 'coris','city' => 2),
array('id' => 3,'name' => 'coris','city' => 2)
);
$order_by = "city desc, name";
echo "<br>ORDER BY $order_by<br>";
$ordered = ordering($data, $order_by);
echo "<pre>";
var_dump($ordered);
echo "</pre>";
我想要做一個排序,如MySQL ORDER BY city DESC, name
。這是我的目標。