English 中文(简体)
如何根据输入数组排序一个数组?
原标题:How to sort an array based on input array?

我无法按照其他数组对数组进行排序。 我尝试过用量、 uksort 和 usort, 但我却一无所获。 其它关于堆叠流的问题在此不直接适用, 因为我的数组结构不同 。 我想排序这个多维数组 :

$main = Array (
    [Technology] => Array ()
    [World] => Array ()
    [Europe] => Array () 
)

使用此索引数组 :

$index = Array (
    [0] => Europe
    [1] => Technology
    [2] => World
)

基本上,在这个例子中,我希望欧洲在$main阵列中排第一,技术第二和世界第三,因为这是他们在$index阵列中的定位。我该怎么做呢? (请忽略上述阵列中的微小语法错误)

最佳回答
$main_sort = array()    
foreach ($index as $key => $value) {
    if ($main [$value]) $main_sorted [$value] = $main [$value];
}

通过 $index 数组简单循环,并用 $main 数组的数值将这些数值映射为新数组。

问题回答

考虑到 $index $main ,

uksort($main, function ($k, $k2) use ($index) {
  return array_search($k, $index) - array_search($k2, $index);
});

矩形将根据 $index 中指定的密钥排序。 不匹配密钥的行为未指明 。

如果您在 $ index 中没有任何值, 而美元 index 在 $ main 中不是一个密钥(例如您的例子中的情况), 此解决方案将有效 :

$sorted = array_merge(array_flip($index), $main);

如果$index 的值是 $main 键的超级集, 可能的解决办法是 :

$sorted = array_intersect_assoc(array_merge(array_flip($index), $main), $main);

切记让 PHP 函数在阵列上工作比“ 明确” 工作要快得多





相关问题
How do I sort enum members alphabetically in Java?

I have an enum class like the following: public enum Letter { OMEGA_LETTER("Omega"), GAMMA_LETTER("Gamma"), BETA_LETTER("Beta"), ALPHA_LETTER("Alpha"), private final String ...

Grokking Timsort

There s a (relatively) new sort on the block called Timsort. It s been used as Python s list.sort, and is now going to be the new Array.sort in Java 7. There s some documentation and a tiny Wikipedia ...

Sorting twodimensional Array in AS3

So, i have a two-dimensional Array of ID s and vote count - voteArray[i][0] = ID, voteArray[i][1] = vote count I want the top 3 voted items to be displayed in different colors, so i have a 2nd Array -...

Linq operations against a List of Hashtables?

I m working with a set of legacy DAO code that returns an IList, where each Hashtable represents the row of a dynamically executed SQL query. For example, the List might contain the following records/...

C++ Array Sort Me

Stuck on an array sorter. Have to sort numbers from largest to smallest. I m trying two loops (one nested in the other). Here s the code: int counter=0; // inner counter int counter2=0; // outer ...

Can I Nest OrderBy in .NET?

This doesn t seem to work as I intend. VB.NET: Dim x = Model.Discussions.OrderByDescending(Function(d) d.Messages.OrderByDescending(Function(m) m.Sent).First.Sent) For Each d As Discussion In x ....

sorting elements javascript

I m looking for a way to sort my elements, but it isn t as easy as it sounds. Please let me explain My elements are grouped per 6 elements (thumbnails), each x represents a thumbnail However all ...

热门标签