PHP:: 按优先级对数组进行双重排序
PHP:: Double sort an array by priority
我的目标是先按字符串长度对数组进行排序,然后在不改变长度优先级的情况下按字符值再次对数组进行排序。
这是我的代码:
$arr=array("an","am","alien","i");
usort($arr, function ($a, $b) { return (strlen($a) <=> strlen($b)); });
print_r($arr);
我得到:
Array ( [0] => i [1] => an [2] => am [3] => alien )
...几乎但不存在)
您缺少解释按字符值排序的逻辑。您可以将该逻辑添加到自定义排序方法中:
// if lengths are the same, then sort by value
if (strlen($a) == strlen($b)) {
return $a <=> $b;
}
// otherwise, sort by length
return (strlen($a) <=> strlen($b));
您可以使用三元组将其合并为一行:
return strlen($a) == strlen($b) ? $a <=> $b : strlen($a) <=> strlen($b);
完整示例 (https://3v4l.org/msISD):
<?php
$arr=array("aa", "az", "an","am", "ba", "by", "alien","i");
usort($arr, function ($a, $b) {
return strlen($a) == strlen($b) ? $a <=> $b : strlen($a) <=> strlen($b);
});
print_r($arr);
输出:
Array
(
[0] => i
[1] => aa
[2] => am
[3] => an
[4] => az
[5] => ba
[6] => by
[7] => alien
)
我的目标是先按字符串长度对数组进行排序,然后在不改变长度优先级的情况下按字符值再次对数组进行排序。
这是我的代码:
$arr=array("an","am","alien","i");
usort($arr, function ($a, $b) { return (strlen($a) <=> strlen($b)); });
print_r($arr);
我得到:
Array ( [0] => i [1] => an [2] => am [3] => alien )
...几乎但不存在)
您缺少解释按字符值排序的逻辑。您可以将该逻辑添加到自定义排序方法中:
// if lengths are the same, then sort by value
if (strlen($a) == strlen($b)) {
return $a <=> $b;
}
// otherwise, sort by length
return (strlen($a) <=> strlen($b));
您可以使用三元组将其合并为一行:
return strlen($a) == strlen($b) ? $a <=> $b : strlen($a) <=> strlen($b);
完整示例 (https://3v4l.org/msISD):
<?php
$arr=array("aa", "az", "an","am", "ba", "by", "alien","i");
usort($arr, function ($a, $b) {
return strlen($a) == strlen($b) ? $a <=> $b : strlen($a) <=> strlen($b);
});
print_r($arr);
输出:
Array
(
[0] => i
[1] => aa
[2] => am
[3] => an
[4] => az
[5] => ba
[6] => by
[7] => alien
)