问题描述
我有一个要对其他数组排序的索引数组:
I have an array of indexes that I want to sort my other array:
$order = [7, 2, 1, 4];
$array = [
1 => "O",
2 => "T"
4 => "F"
7 => "S"
]
如何基于 $ order
数组对 $ array
进行排序,以便输出是..
How can I order the $array
based on $order
array, so that the output is..
$array = [
7 => "S",
2 => "T"
1 => "O",
4 => "F"
]
据我所读,除了for循环外,其他东西都是更可取的
推荐答案
您可以使用 uksort
和 array_search
:
You could make use of uksort
and array_search
:
uksort($array, static function (int $key1, int $key2) use ($order): int {
return array_search($key1, $order, true) <=> array_search($key2, $order, true);
});
想法是根据数组在 $ order
数组中的项的键的位置对数组进行排序:
The idea is to sort the array by the positions of its items' keys within the $order
array:
-
uksort
是一种排序功能,可基于数组键(此处为1、2、4和7)进行排序, -
array_search($ key1,$ order,true)
为您提供$ key1
在$ order
, 中的位置 -
array_search($ key2,$ order,true)
为您提供$ key2
在$ order
, 中的位置 -
< =>
(称为)比较这些值,以便排序首先放置较低的值(在$ order
中位于较低的位置).
uksort
is a sorting function that allows sorting based on array keys (here 1, 2, 4 and 7),array_search($key1, $order, true)
gives you$key1
's position within$order
,array_search($key2, $order, true)
gives you$key2
's position within$order
,<=>
(known as the spaceship operator) compares these values, so that the sorting puts lower values (aka lower positions within$order
) first.
注意:如果数组很大,性能可能会很差,因为 array_search
将在同一键上运行多次.如果这是一个问题,您可以做的是先获取 $ order
中所有键的位置,然后根据它们进行排序.
Note: performance could be bad if your array is big, as array_search
will be run several times on the same keys. If that's an issue, what you can do is grab all keys' positions within $order
first, then sort based on them.
这篇关于排序[键=>[值]由另一个具有相同索引的键数组组成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!