php 二位数组排序

场景:在二维数组中,想根据某一列对数组进行排序

代码 


/**
 * 二维数组排序
 * @param array $arr 要排序的数组
 * @param string $col_key $arr 根据哪一列
 * @param string $sort_type desc:降序 asc:升序
 * @param string $sort_key_type 排序类型 SORT_NUMERIC|SORT_STRING
 */
function array_multi_sort($arr , $col_key , $sort_type = 'desc' , $sort_key_type = SORT_NUMERIC){
	$type = SORT_DESC;
	if($sort_type == 'asc'){
		$type = SORT_ASC;
	}
	$col_arr = array_column($arr, $col_key);
	array_multisort($col_arr,$sort_key_type, $type ,$arr );
	// array_multisort($col1_arr,$sort_key_type, $type ,$col2_arr, $sort_key_type, $type ,$arr );
	return $arr;
}

输出


$arr = [
	[
		'id' => 1,
		'name' => '张1',
		'age' => 28
	],
	[
		'id' => 3,
		'name' => '张3',
		'age' => 21
	],
	[
		'id' => 2,
		'name' => '张2',
		'age' => 23
	],
	[
		'id' => 8,
		'name' => '张8',
		'age' => 13
	],
	[
		'id' => 3,
		'name' => '张4',
		'age' => 17,
	],
];
echo "<pre />";
var_dump(array_multi_sort($arr,'age','asc'));
// array(5) {
//   [0]=>
//   array(3) {
//     ["id"]=>
//     int(8)
//     ["name"]=>
//     string(4) "张8"
//     ["age"]=>
//     int(13)
//   }
//   [1]=>
//   array(3) {
//     ["id"]=>
//     int(3)
//     ["name"]=>
//     string(4) "张4"
//     ["age"]=>
//     int(17)
//   }
//   [2]=>
//   array(3) {
//     ["id"]=>
//     int(3)
//     ["name"]=>
//     string(4) "张3"
//     ["age"]=>
//     int(21)
//   }
//   [3]=>
//   array(3) {
//     ["id"]=>
//     int(2)
//     ["name"]=>
//     string(4) "张2"
//     ["age"]=>
//     int(23)
//   }
//   [4]=>
//   array(3) {
//     ["id"]=>
//     int(1)
//     ["name"]=>
//     string(4) "张1"
//     ["age"]=>
//     int(28)
//   }
//}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值