Home > php教程 > php手册 > php比较多维数组中值的大小排序实现代码

php比较多维数组中值的大小排序实现代码

WBOY
Release: 2016-06-13 11:57:46
Original
1489 people have browsed it

如果值没有重复的情况,可以先用array_flip()来交换键和值,然后krsort(),最后再array_flip()交换回来,就可以比较大小了。如果要截取数组,可用array_slice()。

如果有值重复的情况,就要用到一些排序算法了,不过php有很强大的函数uasort(),使用自定义的比较函数对数组中的值进行排序并保持索引关联,usort()则会重建索引。

复制代码 代码如下:


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 => 人人,
vote_num => 1
),

1 => Array
(
o_id => 1844,
o_name => 芭比,
o_pic => 'http://upload.jb51.net/game_image/dfxxz/dfVIP.files/shenxiandao.jpg',
o_detail => 也是美女呢,
vote_num => 2
),

2 => Array
(
o_id => 1843,
o_name => 程程,
o_pic => 'http://g.jb51.net./upload_img/2011-06/31554_4d0088da7a61ad9c8c02a530be94d98e.png',
o_detail => 美女哦,
vote_num => 3
)
);
uasort($arr, ”cmp“);
echo ‘';
print_r ($arr);
echo ‘';


返回

复制代码 代码如下:


Array
(
[2] => Array
(
[o_id] => 1843
[o_name] => 程程
[o_pic] => http://g.jb51.net./upload_img/2011-06/31554_4d0088da7a61ad9c8c02a530be94d98e.png
[o_detail] => 美女哦
[vote_num] => 3
)
[1] => Array
(
[o_id] => 1844
[o_name] => 芭比
[o_pic] => http://upload.jb51.net/game_image/dfxxz/dfVIP.files/shenxiandao.jpg
[o_detail] => 也是美女呢
[vote_num] => 2
)
[0] => Array
(
[o_id] => 1861
[o_name] => 2
[o_pic] => http://g.jb51.net/image.gif
[o_detail] => 人人
[vote_num] => 1
)
)

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template