如何仅重排原二维数组中指定元素的顺序
自定义排序:仅调整指定元素顺序,其余保持原位
现有两个二维数组,一个是原始数据数组,另一个包含部分相同元素但顺序已调整。需求为:对原始数组排序,仅将新顺序数组中指定的元素调整为对应顺序,其余元素保持原有位置不变。
示例数据
原始数组
[ ['tabelle_mannschaft' => 'SV Winter'], ['tabelle_mannschaft' => 'Mannschaft 7'], ['tabelle_mannschaft' => 'TSV HORIZONT'], ['tabelle_mannschaft' => 'Mannschaft 8'], ]
新顺序数组
[ ['tabelle_mannschaft' => 'TSV HORIZONT'], ['tabelle_mannschaft' => 'Mannschaft 7'], ]
期望结果
[ ['tabelle_mannschaft' => 'SV Winter'], ['tabelle_mannschaft' => 'TSV HORIZONT'], ['tabelle_mannschaft' => 'Mannschaft 7'], ['tabelle_mannschaft' => 'Mannschaft 8'], ]
实现思路
- 为新顺序数组中的元素建立优先级映射,记录每个元素的排序索引
- 从原始数组中筛选出需要调整顺序的元素,按照优先级排序
- 遍历原始数组,遇到需要调整的元素时用排序后的结果替换,其余元素直接保留原位
PHP 实现代码
<?php // 原始数组 $original = [ ['tabelle_mannschaft' => 'SV Winter'], ['tabelle_mannschaft' => 'Mannschaft 7'], ['tabelle_mannschaft' => 'TSV HORIZONT'], ['tabelle_mannschaft' => 'Mannschaft 8'], ]; // 新顺序数组 $newOrder = [ ['tabelle_mannschaft' => 'TSV HORIZONT'], ['tabelle_mannschaft' => 'Mannschaft 7'], ]; // 构建优先级映射表 $priorityMap = []; foreach ($newOrder as $idx => $item) { $priorityMap[$item['tabelle_mannschaft']] = $idx; } // 提取需要排序的元素并按优先级排序 $targetItems = array_filter($original, function($item) use ($priorityMap) { return isset($priorityMap[$item['tabelle_mannschaft']]); }); usort($targetItems, function($a, $b) use ($priorityMap) { return $priorityMap[$a['tabelle_mannschaft']] - $priorityMap[$b['tabelle_mannschaft']]; }); // 合并生成最终数组 $result = []; $targetIdx = 0; foreach ($original as $item) { $val = $item['tabelle_mannschaft']; if (isset($priorityMap[$val])) { $result[] = $targetItems[$targetIdx++]; } else { $result[] = $item; } } // 输出结果 print_r($result); ?>
说明
该逻辑支持任意数量元素的场景,只要新顺序数组中的元素在原始数组中存在,就能精准调整它们的顺序,其余元素的位置完全保留原始数组的状态。
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

