問題描述
我正在嘗試做與 MySQL 查詢相同的操作
I'm trying to do the same as MySQL query
SELECT * FROM table ORDER BY field1, field2, ...
但是使用 php 和一個多維數組:
but with php and a multidimensional array:
$Test = array(
array("a"=>"004", "n"=>"03"),
array("a"=>"003", "n"=>"02"),
array("a"=>"001", "n"=>"02"),
array("a"=>"005", "n"=>"01"),
array("a"=>"001", "n"=>"01"),
array("a"=>"004", "n"=>"02"),
array("a"=>"003", "n"=>"01"),
array("a"=>"004", "n"=>"01")
);
function msort(&$array, $keys){
array_reverse($keys);
foreach($keys as $key){
uasort($array, sortByKey);
}
//
function sortByKey($A, $B){
global $key;
$a = $A[$key];
$b = $B[$key];
if($a==$b) return 0;
return ($a < $b)? -1 : 1 ;
}
}
//
msort($Test, array("a","n"));
//
foreach($Test as $t){
echo('<p>'.$t["a"].'-'.$t["n"].'</p>');
}
我的理論是:如果我對重要性較低"的列進行多次排序,然后對重要性較高"的列進行排序,我將獲得類似于上述 MySQL 查詢的順序.
My theory is: if I sort multiple times on columns with "lesser importance" then columns of "greater importance", I'll achieve an order like the above MySQL query.
不幸的是,php 正在返回:
Unfortunately, php is returning:
警告:uasort() 期望參數 2 是一個有效的回調,在第 23 行的/Library/WebServer/Documents/www/teste.array_sort.php 中找不到函數sortByKey"或無效的函數名稱"(uasort 行)
Warning: uasort() expects parameter 2 to be a valid callback, function 'sortByKey' not found or invalid function name in /Library/WebServer/Documents/www/teste.array_sort.php on line 23" (uasort line)
這是一個簡單的訂單功能.我錯過了什么?
It's a simple order function. What am I missing?
推薦答案
從根本上說,我們將使用與 此處所述相同的方法,我們只是用可變數量的鍵來做:
Fundamentally we're going to use the same approach as explained here, we're just going to do it with a variable number of keys:
/**
* Returns a comparison function to sort by $cmp
* over multiple keys. First argument is the comparison
* function, all following arguments are the keys to
* sort by.
*/
function createMultiKeyCmpFunc($cmp, $key /* , keys... */) {
$keys = func_get_args();
array_shift($keys);
return function (array $a, array $b) use ($cmp, $keys) {
return array_reduce($keys, function ($result, $key) use ($cmp, $a, $b) {
return $result ?: call_user_func($cmp, $a[$key], $b[$key]);
});
};
}
usort($array, createMultiKeyCmpFunc('strcmp', 'foo', 'bar', 'baz'));
// or
usort($array, createMultiKeyCmpFunc(function ($a, $b) { return $a - $b; }, 'foo', 'bar', 'baz'));
這大約相當于 SQL ORDER BY foo, bar, baz
.
That's about equivalent to an SQL ORDER BY foo, bar, baz
.
當然,如果每個鍵都需要不同類型的比較邏輯,并且您不能對所有鍵使用通用的 strcmp
或 -
,那么您將回到相同的代碼如此處所述.
If of course each key requires a different kind of comparison logic and you cannot use a general strcmp
or -
for all keys, you're back to the same code as explained here.
這篇關于如何按多列對多維數組進行排序?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!