Home > Backend Development > PHP Tutorial > PHP compares the size of values ​​in multi-dimensional arrays and sorts the implementation code_PHP tutorial

PHP compares the size of values ​​in multi-dimensional arrays and sorts the implementation code_PHP tutorial

WBOY
Release: 2016-07-21 15:15:38
Original
1366 people have browsed it

If there are no duplicate values, you can first use array_flip() to exchange the keys and values, then krsort(), and finally exchange them back with array_flip() to compare the sizes. If you want to intercept an array, use array_slice().

If there are duplicate values, some sorting algorithm will be used. However, PHP has a very powerful function uasort(), which uses a custom comparison function to sort the values ​​in the array and maintain the index association. , usort() will rebuild the index.

Copy code The 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 => Renren,
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 => She is also a beauty,
vote_num => 2
),

2 => Array
(
o_id => 1843,
o_name => Cheng Cheng,
o_pic => 'http://g.jb51.net./upload_img/2011-06/31554_4d0088da7a61ad9c8c02a530be94d98e.p ng ',
o_detail => Beauty,
vote_num => 3
)
);
uasort($arr, ”cmp“);
echo '< pre style="text-align:left" >';
print_r ($arr);
echo '< / pre >';

return
Copy code The code is as follows:

Array
(
[2] => Array
(
[ o_id] => 1843
[o_name] => Cheng Cheng
[o_pic] => http://g.jb51.net./upload_img/2011-06/31554_4d0088da7a61ad9c8c02a530be94d98e.png
[ o_detail] => Beauty
[vote_num] => 3
)
[1] => Array
(
[o_id] => 1844
[o_name ] => Barbie
[o_pic] => http://upload.jb51.net/game_image/dfxxz/dfVIP.files/shenxiandao.jpg
[o_detail] => She is also a beauty
[vote_num] => 2
)
[0] => Array
(
[o_id] => 1861
[o_name] => 2
[o_pic ] => http://g.jb51.net/image.gif
[o_detail] => 人人
[vote_num] => 1
)
)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326033.htmlTechArticleIf there are no duplicate values, you can first use array_flip() to exchange keys and values, and then krsort(), Finally, swap it back with array_flip(), and you can compare the sizes. If you want to intercept the array, you can...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template