PHP 对二维数组中某个键值排序

使用 usort()对一个二维数组中的某一个键值进行排序.文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
$arr = [
[
'name' => '小明',
'age' => 18,
'sex' => '男'
],
[
'name' => '小园',
'age' => 18,
'sex' => '男'
],
[
'name' => '小花',
'age' => 19,
'sex' => '男'
],
[
'name' => '婷婷',
'age' => 28,
'sex' => '女'
],
[
'name' => '嘻嘻',
'age' => 28,
'sex' => '男'
]
]

$new_arr = usort($arr,function($a,$b){
if($a['age'] == $b['age']){
return 0;
}
return ($a['age'] > $b['age']) ? 1 : -1;
});
# 依据返回值-1,0,1来对$arr升降序排序

重点是usort使用了什么排序算法呢?文档中有个例子提出这一疑问

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
$priorities = array(5, 8, 3, 7, 3);

usort($priorities, function($a, $b)
{
if ($a == $b)
{
echo "a ($a) is same priority as b ($b), keeping the same\n";
return 0;
}
else if ($a > $b)
{
echo "a ($a) is higher priority than b ($b), moving b down array\n";
return -1;
}
else {
echo "b ($b) is higher priority than a ($a), moving b up array\n";
return 1;
}
});

echo "Sorted priorities:\n";
var_dump($priorities);
?>

Output:

b (8) is higher priority than a (3), moving b up array
b (5) is higher priority than a (3), moving b up array
b (7) is higher priority than a (3), moving b up array
a (3) is same priority as b (3), keeping the same
a (8) is higher priority than b (3), moving b down array
b (8) is higher priority than a (7), moving b up array
b (8) is higher priority than a (5), moving b up array
b (8) is higher priority than a (3), moving b up array
a (5) is higher priority than b (3), moving b down array
a (7) is higher priority than b (5), moving b down array

Sorted priorities:
array(5) {
[0]=> int(8)
[1]=> int(7)
[2]=> int(5)
[3]=> int(3)
[4]=> int(3)
}

好像是快速排序的方式。

好了该抛的”砖”也已经抛了,现在该把我们的”玉”引出来啦!

排序算法

先贴个参考链接!

以后补上心得!