Php compares the size sorting implementation code of the values in a multi-dimensional array

Source: Internet
Author: User

If the values are not repeated, you can use array_flip () to exchange keys and values, then krsort (), and then array_flip () to compare the values. Array_slice () is available to intercept arrays ().

If there are duplicate values, some sorting algorithms will be used, but php has a very powerful function uasort (), use a custom comparison function to sort the values in the array and maintain the index Association. usort () re-creates the index.

Copy codeThe Code is as follows: 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.jb51.net/image.gif ',
O_detail => everybody,
Vote_num => 1
),

1 => Array
(
O_id => 1844,
O_name => Barbie,
O_pic => 'HTTP: // upload.jb51.net/game_image/dfxxz/dfVIP.files/shenxiandao.jpg ',
O_detail => what about beautiful women,
Vote_num => 2
),

2 => Array
(
O_id => 1843,
O_name => Cheng,
O_pic => 'HTTP: // g.jb51.net./upload_img/2011-06/31554 _4d0088da7a61ad9c8c02a530be94d98e.png ',
O_detail => pretty girl,
Vote_num => 3
)
);
Uasort ($ arr, "cmp");
Echo '<pre style = "text-align: left"> ';
Print_r ($ arr );
Echo '</pre> ';

ReturnCopy codeThe Code is as follows: Array
(
[2] => Array
(
[O_id] = & gt; 1843
[O_name] => Cheng
[O_pic] => http://g.jb51.net./upload_img/2011-06/31554 _4d0088da7a61ad9c8c02a530be94d98e.png
[O_detail] => pretty girl
[Vote_num] => 3
)
[1] => Array
(
[O_id] = & gt; 1844
[O_name] => Barbie
[O_pic] => http://upload.jb51.net/game_image/dfxxz/dfVIP.files/shenxiandao.jpg
[O_detail] => what about beautiful women?
[Vote_num] => 2
)
[0] => Array
(
[O_id] = & gt; 1861
[O_name] => 2
[O_pic] => http://g.jb51.net/image.gif
[O_detail] => Renren
[Vote_num] => 1
)
)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.