关于排序一般我们都是通过数据库或者nosql(eg:redis)先排好序然后输出到程序里直接使用,但是有些时候我们需要通过PHP直接来对数组进行排序,而在PHP里存储数据用到最多的就是对象和数组,但处理较多的就是数组,因为有非常丰富的内置函数库(其实对象一定程度上也可以理解为是数组),这些函数库很大程度上可以帮助我们实现某些功能。常用的系统函数有sort、asort、arsort、ksort、krsort等等,这里我主要说下对二维数组的排序,两种方法:
A、用PHP自带array_multisort函数排序
复制代码 代码如下:
<?php
$data = array();
$data[] = array(‘volume’ => 67, ‘edition’ => 2);
$data[] = array(‘volume’ => 86, ‘edition’ => 1);
$data[] = array(‘volume’ => 85, ‘edition’ => 6);
$data[] = array(‘volume’ => 98, ‘edition’ => 2);
$data[] = array(‘volume’ => 86, ‘edition’ => 6);
$data[] = array(‘volume’ => 67, ‘edition’ => 7);
// 取得列的列表
foreach ($data as $key => $row)
{
$volume[$key] = $row[‘volume’];
$edition[$key] = $row[‘edition’];
}
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
print_r($data);
?>
输出结果:
复制代码 代码如下:
Array
(
[0] => Array
(
[volume] => 98
[edition] => 2
)
[1] => Array
(
[volume] => 86
[edition] => 1
)
[2] => Array
(
[volume] => 86
[edition] => 6
)
[3] => Array
(
[volume] => 85
[edition] => 6
)
[4] => Array
(
[volume] => 67
[edition] => 2
)
[5] => Array
(
[volume] => 67
[edition] => 7
)
)
关于array_multisort官方文档也有比较详细的说明:
B、自定义函数排序1
复制代码 代码如下:
<?php
$data = array();
$data[] = array(‘volume’ => 67, ‘edition’ => 2);
$data[] = array(‘volume’ => 86, ‘edition’ => 1);
$data[] = array(‘volume’ => 85, ‘edition’ => 6);
$data[] = array(‘volume’ => 98, ‘edition’ => 2);
$data[] = array(‘volume’ => 86, ‘edition’ => 6);
$data[] = array(‘volume’ => 67, ‘edition’ => 7);
// 取得列的列表
foreach ($data as $key => $row)
{
$volume[$key] = $row[‘volume’];
$edition[$key] = $row[‘edition’];
}
$ret = arraySort($data, ‘volume’, ‘desc’);
print_r($ret);
/**
* @desc arraySort php二维数组排序 按照指定的key 对数组进行排序
* @param array $arr 将要排序的数组
* @param string $keys 指定排序的key
* @param string $type 排序类型 asc | desc
* @return array
*/
function arraySort($arr, $keys, $type = ‘asc’) {
$keysvalue = $new_array = array();
foreach ($arr as $k => $v){
$keysvalue[$k] = $v[$keys];
}
$type == ‘asc’ ? asort($keysvalue) : arsort($keysvalue);
reset($keysvalue);
foreach ($keysvalue as $k => $v) {
$new_array[$k] = $arr[$k];
}
return $new_array;
}
?>
输出结果:
复制代码 代码如下: