Sorting a multidimensional array?

后端 未结 2 1894
借酒劲吻你
借酒劲吻你 2021-01-06 21:57

I have an array that looks like this:

Array ( [0] => Array ( [filters] => Array ( [filter_1] => 1 
                                            [filt         


        
相关标签:
2条回答
  • 2021-01-06 22:00

    You'll need to use the uasort function. Try something like this:

    function cmp($a, $b) {
        if ($a["count"] == $b["count"]) {
            return 0;
        }
        return ($a["count"] > $b["count"]) ? -1 : 1;
    }
    
    uasort($array, 'cmp');
    
    0 讨论(0)
  • 2021-01-06 22:25

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

    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.

    For example:

    usort($array, "byCount");
    
    function byCount($a, $b)
    {
        if( $a['count'] == $b['count'] )
        {
            return 0;
        }
        return ($a['count'] < $b['count']) ? -1 : 1;
    }
    
    0 讨论(0)
提交回复
热议问题