English 中文(简体)
依列之一排序 2d 数组
原标题:Sort 2d array by one of its columns
[
    1 => [ id  => 1,  sort  => 1],
    3 => [ id  => 3,  sort  => 3],
    2 => [ id  => 2,  sort  => 2],
]

How do I sort it so that it s re-ordered using the inner sort key? Desired result:

[
    1 => [ id  => 1,  sort  => 1],
    2 => [ id  => 2,  sort  => 2],
    3 => [ id  => 3,  sort  => 3],
]
问题回答

您可以使用 < a href=> "http://php.net/usort" rel="noreferrer"\\ code>usort 使用此比较函数 :

function cmpBySort($a, $b) {
    return $a[ sort ] - $b[ sort ];
}
usort($arr,  cmpBySort );

或者您使用 < a href=> "http://php.net/array_multisort" rel="noreferrer"\\code>ary_multisort 并附加排序顺序的关键值数列 :

$keys = array_map(function($val) { return $val[ sort ]; }, $arr);
array_multisort($keys, $arr);

这里 < a href=>" "http://php.net/array_map" rel="noreferr"\\\ code>array_map 与annonymous 函数 用来构建用于排序数组值本身的 sort 数值阵列数组。 其优点在于对每对数值都需要 Np 比较函数 。

像这样的事情:

usort($array, function (array $a, array $b) { return $a["sort"] - $b["sort"]; });

像这样的事情:

uasort($array,  compfunc );

function compfunc($a, $b)
{
    return $a[ sort ] - $b[ sort ];
}




相关问题
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 ...

热门标签