开发者

Sorting multi-dimensional arrays [duplicate]

This question already has answers here: How can I sort arrays and data in PHP? (14 answers) Closed 8 years ago. 开发者_C百科

I have an array like this:

Array ( 
    [0] => Array ( 
        [tag] => /nn 
        [count] => 55
    ) 
    [1] => Array ( 
        [tag] => /vb 
        [count] => 7
    )
) 

and I want to sort it. In this example it's already like I want it to be. Sorted by count. What if it was reverse ordered? What function is there to sort it?

Thanks a lot.


Check this code

function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
    $sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
    $ret[$ii]=$array[$ii];
}
$array=$ret;
}
aasort($your_array,"order");

Or

I usually use usort, and pass my own comparison function. In this case, it is very simple:

function sortByOrder($a, $b) {
return $a['order'] - $b['order'];
}
usort($myArray, 'sortByOrder');

Hope you can find your answer. Mark my answer and point me up, thanks.


$count = array();

// Obtain a list of columns
foreach ($array as $key => $row) {
    $count[$key]  = $row['count'];
}

//sort by count descending
array_multisort($count, SORT_DESC, $array);

DOC


Use usort() like this:

 usort( $array, function( $a, $b ) { 
     if ( $a['count'] == $b['count'] ) 
         return 0;

     return ( $a['count'] > $b['count'] ? -1 : 1 );
 }

Reverse the > if you want it to reverse the order.


I 've written a function here that allows you to select which key you want to sort with. You can even specify multiple keys for secondary, tertiary, etc sort.

With this make_comparer function, you would sort like this:

uasort($array, make_comparer('count'));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜