本文实例讲述了PHP实现二维数组按指定的键名排序的方法。分享给大家供大家参考,具体如下:
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
46
47
48
49
|
<?php
/*二维数组按指定的键值排序*/
function array_sort( $array , $keys , $type = 'asc' ){
if (!isset( $array ) || ! is_array ( $array ) || empty ( $array )){
return '' ;
}
//排序字段名,如:id
if (!isset( $keys ) || trim( $keys )== '' ){
return '' ;
}
//排序方式,如:desc、asc
if (!isset( $type ) || $type == '' || !in_array( strtolower ( $type ), array ( 'asc' , 'desc' ))){
return '' ;
}
//定义一个数组
$keysvalue = array ();
foreach ( $array as $key => $val ){
//对排序字段值进行过滤
$val [ $keys ] = str_replace ( '-' , '' , $val [ $keys ]);
$val [ $keys ] = str_replace ( ' ' , '' , $val [ $keys ]);
$val [ $keys ] = str_replace ( ':' , '' , $val [ $keys ]);
//将记录中指定的键名放入数组中,如:[0]=>5,[1]=>3,[2]=>6
$keysvalue [] = $val [ $keys ]; //排序字段,如:id 索引=》排序键名
}
asort( $keysvalue ); //按值升序排序,且保持键名与键值之间的索引关系,如:[1]=>3,[0]=>5,[2]=>6
reset( $keysvalue ); //指针重新指向数组第一个
foreach ( $keysvalue as $key => $vals ) {
$keysort [] = $key ; //0=>[1],1=>[0],2=>[2]
}
$keysvalue = array ();
$count = count ( $keysort ); //排序记录数
if ( strtolower ( $type ) != 'asc' ){ //降序
for ( $i = $count -1; $i >=0; $i --) {
$keysvalue [] = $array [ $keysort [ $i ]];
}
} else { //升序
for ( $i =0; $i < $count ; $i ++){
$keysvalue [] = $array [ $keysort [ $i ]];
}
}
return $keysvalue ;
}
$array = array (
array ( 'name' => 'Tom' , 'age' => '23' , 'like' => 'beer' ),
array ( 'name' => 'Trump' , 'age' => '50' , 'like' => 'Food' ),
array ( 'name' => 'Jack' , 'age' => '26' , 'like' => 'Travel' )
);
print_r(array_sort( $array , 'age' ));
?>
|
运行结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
Array
(
[0] => Array
(
[name] => Tom
[age] => 23
[like] => beer
)
[1] => Array
(
[name] => Jack
[age] => 26
[like] => Travel
)
[2] => Array
(
[name] => Trump
[age] => 50
[like] => Food
)
)
|
希望本文所述对大家PHP程序设计有所帮助。
原文链接:http://blog.csdn.net/yanhui_wei/article/details/8574630