您的位置:首页 > 编程语言 > PHP开发

php三种方式对二维数组进行花样排序

2017-08-27 17:19 302 查看
以下分别使用了冒泡排序,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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: