Created
October 27, 2017 03:38
-
-
Save cute-angelia/efc867e20e6bf894040f332de00d7c9b to your computer and use it in GitHub Desktop.
PHP 对二维数组指定key排序
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1、利用php array_multisort函数 | |
// 参数:$arr 二维数组 ,$key 需要排序的列 $type 排序类型 $short 排序方式 | |
``` | |
function multi_array_sort($arr,$key,$type=SORT_REGULAR,$short=SORT_DESC){ | |
foreach ($arr as $k => $v){ | |
$name[$k] = $v[$key]; | |
} | |
array_multisort($name,$type,$short,$arr); | |
return $arr; | |
} | |
``` | |
2、获取key值,进行排序,然后整理成二维数组 | |
``` | |
function array_sort($arr,$key,$type='asc'){ | |
$keysvalue = $new_array = array(); | |
// 获取key | |
foreach ($arr as $k=>$v){ | |
$keysvalue[$k] = $v[$key]; | |
} | |
// key排序 | |
if($type == 'asc'){ | |
asort($keysvalue); | |
}else{ | |
arsort($keysvalue); | |
} | |
reset($keysvalue); | |
// 根据key排序整理正确二维数组顺序 | |
foreach ($keysvalue as $k=>$v){ | |
$new_array[$k] = $arr[$k]; | |
} | |
return $new_array; | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment