二维数组排序

写个函数用来对二维数组排序

$data = [
['key1'=>940,'key2'=>'blah'],
['key1'=>23,'key2'=>'this'],
['key1'=>894,'key2'=>'that']
];
比如以key1排序

方法一:

$data = [
    ['key1'=>940,'key2'=>'blah'],
    ['key1'=>23,'key2'=>'this'],
    ['key1'=>894,'key2'=>'that']
];
foreach ($data as $key=>$value){
    $key1[$key] = $value['key1'];
    $key2[$key] = $value['key2'];
}
array_multisort($key1,SORT_NUMERIC,SORT_DESC,$key2,SORT_STRING,SORT_ASC,$data);
var_dump($data);

方法二:

$data = [
    ['key1'=>940,'key2'=>'blah'],
    ['key1'=>23,'key2'=>'this'],
    ['key1'=>894,'key2'=>'that']
];
function mySort($arr,$key){
    $arr = array_column($arr,null,$key);
    ksort($arr);
    return $arr;
}
var_dump(mySort($data,'key2'));

方法三:

$data = [
    ['key1'=>940,'key2'=>'blah'],
    ['key1'=>23,'key2'=>'this'],
    ['key1'=>894,'key2'=>'that']
];
function myArraySort($data,$key,$desc=true){
	if(empty($data)){
		return $data;
	}
	usort($data, function($a, $b) use ($key,$desc) {
		if($desc){
			return strcmp($b[$key],$a[$key]);
		}
		return strcmp($a[$key],$b[$key]);
	});
	return $data;
}
var_dump(myArraySort($data,'key2'));
posted @ 2023-03-09 09:38  成文的博客  阅读(47)  评论(0编辑  收藏  举报