排序多维数组? [英] Sorting a multidimensional array?

查看:46
本文介绍了排序多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数组:

I have an array that looks like this:

Array ( [0] => Array ( [filters] => Array ( [filter_1] => 1 
                                            [filter_2] => 1 
                                            [filter_3] => 1 
                                            [filter_4] => 1 
                                            [filter_5] => 1 
                                            [filter_6] => 1 ), 
                       [count]   => 2),

        [1] => Array ( [filters] => Array ( [filter_1] => 1 
                                            [filter_2] => 1 
                                            [filter_3] => 1 
                                            [filter_4] => 1 
                                            [filter_5] => 1 
                                            [filter_6] => 1 ), 
                       [count]   => 34)

        [2] => Array ( [filters] => Array ( [filter_1] => 1 
                                            [filter_2] => 1 
                                            [filter_3] => 1 
                                            [filter_4] => 1 
                                            [filter_5] => 1 
                                            [filter_6] => 1 ), 
                        [count]   => 7)

是否可以通过每个[count]键对主数组键进行降序排序?因此它们的顺序如下:1 -2 -0

Is it possible to sort the main array keys by the [count] key in each, descending? So that they are in the following order: 1 -2 -0

推荐答案

您绝对希望 usort 函数.您可以定义排序功能如何确定较大还是较小.

You definitely want the usort function. You can define how the sort function determines which is larger or smaller.

如果可以正确地对每个子数组(过滤器"和计数")进行重新索引,那么这应该可以正常工作.通过重新索引,我的意思是新排序的数组将从0开始,逐渐增长到1,依此类推.除非您原来的数组是关联的,否则这几乎总是您想要的方式.

If it's alright that each sub-array (of "filters" and "count") gets re-indexed, this should work perfectly. By re-indexed, I mean the newly sorted array would start at 0, progress to 1, etc. This is almost always how you want it, unless your original array is associative.

例如:

usort($array, "byCount");

function byCount($a, $b)
{
    if( $a['count'] == $b['count'] )
    {
        return 0;
    }
    return ($a['count'] < $b['count']) ? -1 : 1;
}

这篇关于排序多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆