PHP二维数组重构:保留一级键的数组转置(按索引合并列值)
按索引列合并二维数组的实现方案
场景回顾
现有PHP数组:
$parent = [ 1 => ['test1', 'test2'], 2 => ['test1_1', 'test2_2'], ];
需要将相同索引位置的元素按列分组,得到结果:
[ 1 => ['test1', 'test1_1'], 2 => ['test2', 'test2_2'], ]
解决方案
方法一:使用array_map快速实现
array_map传入null作为回调时,会自动将多个输入数组的对应索引元素合并为新数组,是最简洁的实现方式:
$parent = [ 1 => ['test1', 'test2'], 2 => ['test1_1', 'test2_2'], ]; // 提取所有子数组并按索引合并 $temp = array_map(null, ...array_values($parent)); // 将结果的键从0起始改为1起始,匹配需求格式 $result = array_combine(range(1, count($temp)), $temp); print_r($result);
array_values($parent):忽略原父数组的键,提取所有子数组作为后续操作的数据源...:将子数组展开为array_map的多个独立参数array_map(null, $arr1, $arr2):核心逻辑,把两个数组对应索引的元素打包成新子数组array_combine(range(1, count($temp)), $temp):将默认0起始的索引替换为1起始的数字键
方法二:手动循环控制(适合复杂场景)
如果需要处理子数组长度不一致等特殊情况,手动循环能提供更灵活的控制:
$parent = [ 1 => ['test1', 'test2'], 2 => ['test1_1', 'test2_2'], ]; $result = []; // 以第一个子数组的长度作为列数(可根据需求修改为兼容逻辑) $columnCount = count(reset($parent)); for ($col = 0; $col < $columnCount; $col++) { foreach ($parent as $subArr) { // 按列收集元素,键从1开始 $result[$col + 1][] = $subArr[$col]; } } print_r($result);
为什么array_combine不符合需求?
array_combine($keys, $values)的作用是用第一个数组的元素作为键、第二个数组的元素作为值生成关联数组,所以你之前得到的是['test1' => 'test1_1', 'test2' => 'test2_2'],这和按列分组的逻辑完全不同,因此不适用。
内容的提问来源于stack exchange,提问作者mr programmer
相关产品推荐
相关产品推荐

