我有一个数组($myArray)
Array ( [0] =>
Array ( [0] => new
[1] => NFL930
[2] => Ohio
...
)
[1] =>
Array ( [0] => new
[1] => MLB382
[2] => Florida
...
)
[2] =>
Array ( [0] => new
[1] => MLB101
[2] => Vermont
...
)
[3] =>
Array ( [0] => new
[1] => NFL732
[2] => Alabama
...
)
[4] =>
Array ( [0] => old
[1] => MLB490
[2] => Texas
...
)
[5] =>
Array ( [0] => old
[1] => MLB821
[2] => Atlanta
...
)
[6] =>
Array ( [0] => old
[1] => NFL293
[2] => Maine
...
)
.....
)
我有一个对上面显示的 [0] 索引进行排序的函数,因此所有“新”条目都在前面,然后列出所有“旧”条目。
usort($myArray, function($a, $b) use ($myValues){
return $myValues[$a[0]] - $myValues[$b[0]];
});
数组 $myValues 看起来像
Array ( [New] => 0 [Old] => 1 [Other] => 2 )
我想保持 [0] 索引排序,首先显示所有新的数组,然后显示旧的数组,等等。然后我想在 MLB 的数组之前显示带有“NFL”的数组。例如,所需的输出将是
Array ( [0] =>
Array ( [0] => new
[1] => NFL930
[2] => Ohio
...
)
[1] =>
Array ( [0] => new
[1] => NFL732
[2] => Alabama
...
)
[2] =>
Array ( [0] => new
[1] => MLB101
[2] => Vermont
...
)
[3] =>
Array ( [0] => new
[1] => MLB382
[2] => Florida
...
)
[4] =>
Array ( [0] => old
[1] => NFL293
[2] => Maine
...
)
[5] =>
Array ( [0] => old
[1] => MLB821
[2] => Atlanta
...
)
[6] =>
Array ( [0] => old
[1] => MLB490
[2] => Texas
...
)
.....
)
您可以修改您的用户排序:
usort($myArray, function($a, $b) use ($myValues){
if ($myValues[$a[0]] - $myValues[$b[0]] == 0) {
return strcmp($a[1],$b[1]);
}
return $myValues[$a[0]] - $myValues[$b[0]];
});
如果条目在索引 0 上相同,则这将根据索引 1 对条目进行排序(这意味着 NFL 位于 MLB 之前,而且 NFL001 也位于 NFL002 之前)
您可以按第一列然后按第二列的前缀进行自定义排序。
array_multisort()
:(演示)
$priority0 = array_flip(['new', 'old', 'other']);
$priority1 = array_flip(['NFL', 'MLB']);
array_multisort(
array_map(
fn($row) => $priority0[$row[0]] ?? PHP_EOL,
$array
),
array_map(
fn($row) => $priority1[rtrim($row[1], '0..9')] ?? PHP_EOL,
$array
),
$array
);
var_export($array);
或
usort()
:(演示)
$priority0 = array_flip(['new', 'old', 'other']);
$priority1 = array_flip(['NFL', 'MLB']);
usort(
$array,
fn($a, $b) => ($priority0[$a[0]] ?? PHP_EOL) <=> ($priority0[$b[0]] ?? PHP_EOL)
?: ($priority1[rtrim($a[1], '0..9')] ?? PHP_EOL) <=> ($priority1[rtrim($b[1], '0..9')] ?? PHP_EOL)
);
var_export($array);