二维数组根据某个字段排序根据另一个数组排序

按照某个字段 正序或者倒序 排序

$a = [
	['id'=>2,'name'=>'b'],
	['id'=>1,'name'=>'a'],
	['id'=>3,'name'=>'c'],
];
按照id 从小到大排序
$ids = array_column($a,'id');	//[2,1,3]
array_multisort($ids,SORT_ASC,SORT_NUMERIC,$a);
print_r($a);
/*Array ( 
	[0] => Array ( [id] => 1 [name] => a ) 
	[1] => Array ( [id] => 2 [name] => b )
	[2] => Array ( [id] => 3 [name] => c ) 
)*/

按照name顺序 从大到小排序
$names = array_column($a,'name');//Array ( [0] => b [1] => a [2] => c )
array_multisort($names,SORT_DESC,SORT_STRING,$a);
print_r($a);
/*Array (
	 [0] => Array ( [id] => 3 [name] => c ) 
	 [1] => Array ( [id] => 2 [name] => b ) 
	 [2] => Array ( [id] => 1 [name] => a ) 
 )*/

按照另一个数组排序

$a = [
	['id'=>2,'name'=>'b'],
	['id'=>1,'name'=>'a'],
	['id'=>3,'name'=>'c'],
];
$b = [3,1,2];

//根据每条记录的字段id,去$b中查找对应的键值,作为这一条记录的键值。
$newarr = [];
foreach ($a as $v) {
	$k = array_search($v['id'],$b);
	$newarr[$k] = $v;
}
ksort($newarr);

/*Array (
	 [0] => Array ( [id] => 3 [name] => c ) 
	 [1] => Array ( [id] => 1 [name] => a ) 
	 [2] => Array ( [id] => 2 [name] => b ) 
 )*/

你可能感兴趣的:(代码实战)