一個限制而排序長度的基礎上的鍵爲:長度相等鍵不重新排序。假設我們需要按照訂單號descending
的順序排序。
$arr = array(
"foo 0" => "apple",
"foo 1" => "ball",
"foo 2 foo 0 foo 0" => "cat",
"foo 2 foo 0 foo 1 foo 0" => "dog",
"foo 2 foo 0 foo 1 foo 1" => "elephant",
"foo 2 foo 1 foo 0" => "fish",
"foo 2 foo 1 foo 1" => "giraffe"
);
debug($arr, "before sort");
$arrBad = $arr;
sortKeysDescBAD($arrBad);
debug($arrBad, "after BAD sort");
sortKeysDescGOOD($arr);
debug($arr, "after GOOD sort 2");
function sortKeysDescBAD(&$arrNew) {
$arrKeysLength = array_map('strlen', array_keys($arrNew));
array_multisort($arrKeysLength, SORT_DESC, $arrNew);
//return max($arrKeysLength);
}
function sortKeysDescGOOD(&$arrNew) {
uksort($arrNew, function($a, $b) {
$lenA = strlen($a); $lenB = strlen($b);
if($lenA == $lenB) {
// If equal length, sort again by descending
$arrOrig = array($a, $b);
$arrSort = $arrOrig;
rsort($arrSort);
if($arrOrig[0] !== $arrSort[0]) return 1;
} else {
// If not equal length, simple
return $lenB - $lenA;
}
});
}
function debug($arr, $title = "") {
if($title !== "") echo "<br/><strong>{$title}</strong><br/>";
echo "<pre>"; print_r($arr); echo "</pre><hr/>";
}
輸出將是:
before sort
Array
(
[foo 0] => apple
[foo 1] => ball
[foo 2 foo 0 foo 0] => cat
[foo 2 foo 0 foo 1 foo 0] => dog
[foo 2 foo 0 foo 1 foo 1] => elephant
[foo 2 foo 1 foo 0] => fish
[foo 2 foo 1 foo 1] => giraffe
)
after BAD sort
Array
(
[foo 2 foo 0 foo 1 foo 0] => dog
[foo 2 foo 0 foo 1 foo 1] => elephant
[foo 2 foo 0 foo 0] => cat
[foo 2 foo 1 foo 0] => fish
[foo 2 foo 1 foo 1] => giraffe
[foo 0] => apple
[foo 1] => ball
)
after GOOD sort
Array
(
[foo 2 foo 0 foo 1 foo 1] => elephant
[foo 2 foo 0 foo 1 foo 0] => dog
[foo 2 foo 1 foo 1] => giraffe
[foo 2 foo 1 foo 0] => fish
[foo 2 foo 0 foo 0] => cat
[foo 1] => ball
[foo 0] => apple
)
通知elephant
和dog
例如(或其他人)在兩個分揀方法的順序。第二種方法看起來更好。有可能是更簡單的方法來解決這個問題,但希望這可以幫助別人......
也,是否有一個特別的原因,你想在PHP中做到這一點? – Ascherer 2011-12-21 21:09:12
@Ascherer:數據不在MySQL中,我想避免將所有數據都放在那裏的傳輸時間。我的SELECT語句只是一個例子。 – Drahcir 2011-12-21 21:12:05
ahh,k。這很有道理 – Ascherer 2011-12-21 21:23:40