php三种方式对二维数组进行花样排序
以下分别使用了冒泡排序,array_multisort, usort对二维数组进行排序
<?php
$array = [
0 => ["name" => "lele", "score" => 77],
1 => ["name" => "haha", "score" => 100],
2 => ["name" => "xly", "score" => 67],
3 => ["name" => "mao", "score" => 67],
4 => ["name" => "ming", "score" => 98],
];
//冒泡排序
function sort_pop(&$array, $order = "asc")
{
$len = count($array);
if ($order == "asc") {//从小到大排序
for ($i=0; $i < $len; $i++) {
for ($j=$len-1; $j >$i ; $j--) {
if ($array[$j]["score"] < $array[$j - 1]["score"]) {
swap($array[$j], $array[$j - 1]);
}
}
}
} else {//从大到小排序
for ($i=0; $i < $len; $i++) {
for ($j=0; $j < $len-$i-1; $j++) {
if ($array[$j]["score"] < $array[$j + 1]["score"]) {
swap($array[$j], $array[$j+1]);
}
}
}
}
}
function swap(&$a, &$b)
{
$temp = $a;
$a = $b;
$b = $temp;
}
//(1)冒泡排序
sort_pop($array, "asc");
// (2) 使用php自身的函数
// $score = array_column($array, "score");
// $name = array_column($array, "name");
// // 将$array数组按照score 顺序排序,按照name倒序排序
// array_multisort($score, SORT_ASC, SORT_NUMERIC, $name, SORT_DESC, SORT_STRING, $array);
// (3)使用自定义函数进行排序
// usort($array, function ($a, $b) {
// if ($a["score"] == $b["score"]) {
// return 0;
// }
// return $a["score"] < $b["score"] ? -1 : 1;
// });
var_dump($array);exit;
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: Windows系统下Apache性能优化,提高并发
- 下一篇: CentOS 查看硬件信息