如何按另一二维数组对应值排序二维数组,未匹配项后置?
多维数组按指定匹配规则排序问题
我有两个多维数组,需要将第一个数组$allOptions按照第二个数组$regOptions的顺序排序,匹配规则为clID == optID。注意并非所有$allOptions的子数组都能在$regOptions中找到对应项,未匹配的元素需置于数组末尾。
原数组示例
$allOptions = array( array("clID"=> 171, ...other values), array("clID"=> 191, ...other values), array("clID"=> 131, ...other values), array("clID"=> 101, ...other values), array("clID"=> 201, ...other values), array("clID"=> 181, ...other values), ... array("clID"=> 99, ...other values), // 不在regOptions中 array("clID"=> 129, ...other values), // 不在regOptions中 array("clID"=> 139, ...other values) ) ; $regOptions = array( array("order"=>1,"optID"=> 131, ...other values), array("order"=>2,"optID"=> 191, ...other values), array("order"=>3,"optID"=> 181, ...other values), array("order"=>4,"optID"=> 139, ...other values), array("order"=>5,"optID"=> 101, ...other values), array("order"=>6,"optID"=> 201, ...other values), array("order"=>7,"optID"=> 171, ...other values) ... ) ;
预期输出
$allOptions = array( array("clID"=> 131, ...other values), array("clID"=> 191, ...other values), array("clID"=> 181, ...other values), array("clID"=> 139, ...other values), array("clID"=> 101, ...other values), array("clID"=> 201, ...other values), array("clID"=> 171, ...other values), ... array("clID"=> 99, ...other values), // 不在regOptions中 array("clID"=> 129, ...other values) // 不在regOptions中 ) ;
实现方案
- 先构建
$regOptions的映射数组,将optID作为键,对应的order值作为排序权重,方便快速查询:
$orderMap = []; foreach ($regOptions as $item) { $orderMap[$item['optID']] = $item['order']; }
- 使用
usort()函数对$allOptions进行排序,排序逻辑为:
- 若当前元素的
clID存在于映射数组中,使用对应的order值参与排序 - 未匹配的元素赋予一个极大的数值(比如PHP_INT_MAX),确保排在所有匹配元素之后:
usort($allOptions, function($a, $b) use ($orderMap) { $posA = isset($orderMap[$a['clID']]) ? $orderMap[$a['clID']] : PHP_INT_MAX; $posB = isset($orderMap[$b['clID']]) ? $orderMap[$b['clID']] : PHP_INT_MAX; return $posA - $posB; });
- 执行完上述代码后,
$allOptions就会按照预期的顺序排列。
内容的提问来源于stack exchange,提问作者rolinger
相关产品推荐
相关产品推荐

