php compares the size sort implementation code for values in multidimensional arrays
- 2020-05-24 05:16:55
- OfStack
If the values are not repeated, you can swap the keys and values with array_flip(), then krsort(), and finally array_flip() to compare the sizes. If you want to intercept an array, you can use array_slice().
If you have duplicate values, you'll need to use some sorting algorithms, but php has a powerful function called uasort(), which USES a custom comparison function to sort the values in an array and keep the index associated, and usort() to rebuild the index.
return
If you have duplicate values, you'll need to use some sorting algorithms, but php has a powerful function called uasort(), which USES a custom comparison function to sort the values in an array and keep the index associated, and usort() to rebuild the index.
function cmp($a, $b){
if ($a["vote_num"] == $b["vote_num"]) {
return 0;
}
return ($a["vote_num"] > $b["vote_num"]) ? -1 : 1;
}
$arr = Array
(
0 => Array
(
o_id => 1861,
o_name => 2,
o_pic => 'http://g.ofstack.com/image.gif' ,
o_detail => everyone ,
vote_num => 1
),
1 => Array
(
o_id => 1844,
o_name => barbie ,
o_pic => 'http://upload.ofstack.com/game_image/dfxxz/dfVIP.files/shenxiandao.jpg',
o_detail => She's a beauty, too. ,
vote_num => 2
),
2 => Array
(
o_id => 1843,
o_name => Love never fails ,
o_pic => 'http://g.ofstack.com./upload_img/2011-06/31554_4d0088da7a61ad9c8c02a530be94d98e.png',
o_detail => The beauty oh ,
vote_num => 3
)
);
uasort($arr, " cmp " );
echo ' < pre style="text-align:left" >';
print_r ($arr);
echo ' < / pre >';
return
Array
(
[2] => Array
(
[o_id] => 1843
[o_name] => Love never fails
[o_pic] => http://g.ofstack.com./upload_img/2011-06/31554_4d0088da7a61ad9c8c02a530be94d98e.png
[o_detail] => The beauty oh
[vote_num] => 3
)
[1] => Array
(
[o_id] => 1844
[o_name] => barbie
[o_pic] => http://upload.ofstack.com/game_image/dfxxz/dfVIP.files/shenxiandao.jpg
[o_detail] => She's a beauty, too.
[vote_num] => 2
)
[0] => Array
(
[o_id] => 1861
[o_name] => 2
[o_pic] => http://g.ofstack.com/image.gif
[o_detail] => everyone
[vote_num] => 1
)
)