gpt4 book ai didi

php - call_user_func_array 和 array_multisort

转载 作者:行者123 更新时间:2023-11-29 08:49:17 33 4
gpt4 key购买 nike

我遇到排序方向问题。我尝试按方向对多维数组进行排序。我无法使用array_multisort()直接,因为我不知道会有多少个参数。我用call_user_func_array('array_multisort', $params);它有效,但我无法设置排序方向( SORT_ASC,SORT_DESC )。如何设置 call_user_func_array('array_multisort', $params); 的排序方向?这是我的代码,你可以尝试一下

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 的排序。这是我的目标。

最佳答案

为了能够对数组进行多次排序并获得像 ORDER BY city DESC, name ASC 这样的结果,您需要一个执行 stable sort 的函数.
据我所知 PHP 没有这样的函数,所以你必须使用像这样的比较器函数对它进行一次排序

$data = array (
array('id' => 3,'name' => 'coris','city' => 2),
array('id' => 1,'name' => 'Barack','city' => 9),
array('id' => 7,'name' => 'boris','city' => 2),
array('id' => 3,'name' => 'coris','city' => 2),
);

$order_by = array(
'city' => array('dir' => SORT_DESC, 'type' => SORT_NUMERIC),
'name' => array('dir' => SORT_ASC, 'type' => SORT_STRING),
);

function compare($row1,$row2) {
/* this function should determine which row is greater based on all of the criteria
and return a negative number when $row1 < $row2
a positive number when $row1 > $row2
0 when $row1 == $row2
*/

global $order_by;

foreach($order_by as $field => $sort) {
if($sort['type'] != SORT_NUMERIC) {
// strings are compared case insensitive and assumed to be in the mb_internal_encoding
$cmp = strcmp(mb_strtolower($row1[$field]), mb_strtolower($row2[$field]));
} else {
$cmp = doubleval($row1[$field]) - doubleval($row2[$field]);
}
if($sort['dir'] != SORT_ASC) $cmp = -$cmp;
if($cmp != 0) return $cmp;
}
return 0;
}


usort($data,'compare');

关于php - call_user_func_array 和 array_multisort,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11721976/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com