按子元素对数组进行排序的最有效方法?
我有一个多维数组。
$array[0] = array(1, 8, 2);
$array[1] = array(5, 6, 15);
$array[2] = array(-8, 2, 1025);
我想知道通过子数组的特定属性对父数组进行排序的最有效方法是什么。例如,我想将它们按 $sub_array[1] 的升序排列,因此父数组将按 2,1,0 排序。
I have a multidimensional array.
$array[0] = array(1, 8, 2);
$array[1] = array(5, 6, 15);
$array[2] = array(-8, 2, 1025);
I am wondering what the most efficient way to order the parent array by a particular property of it's sub array. For example, I want to put them in ascending order of $sub_array[1], so the parent array would be ordered 2,1,0.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
sort
及其同类有一些变体,其中您可以提供自己的排序回调函数:usort
< /a>,uasort
(其中维护索引)和uksort
(您必须创建自己的排序回调来执行您想要执行的操作,请注意,如果 $subarray[1] 相等,那么我的函数会将两个子数组排序为相等。更具体地说,您可以为
$a[1] == $b[1]
添加更多规则。sort
and its cousins have variations where you can supply your own sorting callback function:usort
,uasort
(which maintains indexes), anduksort
(which sorts on the keys. You'll have to create your own sorting callback to do what you want to do here.Note that my function will sort two subarrays as being equal if $subarray[1] is equal, so if you want to be more specific, you can add more rules for when
$a[1] == $b[1]
.使用 http://www.php.net/manual/en/function.usort .php 并编写一个回调函数来实现您想要的排序条件。
Use http://www.php.net/manual/en/function.usort.php and write a callback function that implements the sort condition you want.