# 怎么把一个数组插入另一个数组的固定位置呢？

352 次浏览

``````//去插入的数组
\$newArray = ['n1' => ['fixed' => 2], 'n2' => ['fixed' => 5], 'n3' => ['fixed' => 8]];

//被插入的数组
\$oldArray = ['o1' => [], 'o2' => [], 'o3' => [], 'o4' => [], 'o5' => [], 'o6' => [], 'o7' => []];

//最终想要的数组
\$res = ['01' => [], 'n1' => [], 'o2' => [], 'o3' => [], 'n2' => [], 'o4' => [], 'o5' => [], 'n3' => [], 'o6' => [], 'o7' => []];

``````

\$oldArray可以根据循环的时候，把\$key+1，拿到对应的排序；1...n这样；

\$newArray的fixed字段就是我们手动排序的固定位置；

\$res是我们最终想要的数组；

2019-05-18 提问

## 查看全部 2 个回答

``````<?php
//去插入的数组
\$newArray = ['n1' => ['fixed' => 2], 'n2' => ['fixed' => 5], 'n3' => ['fixed' => 8]];
//被插入的数组
\$oldArray = ['o1' => [], 'o2' => [], 'o3' => [], 'o4' => [], 'o5' => [], 'o6' => [], 'o7' => []];

\$i = 1;
foreach (\$oldArray as \$key => \$value) {
\$temp_arr[\$key] = \$value;
\$num_key = substr(\$key, 1);
if (0 !== \$num_key % 2) {
\$temp_arr['n' . \$i] = \$newArray['n' . \$i];
\$i++;
}
}
\$res = \$temp_arr;
print_r(\$res);``````

## 推荐答案

``````<?php
//去插入的数组
\$newArray = ['n1' => ['fixed' => 2], 'n2' => ['fixed' => 5], 'n3' => ['fixed' =>8]];
//被插入的数组
\$oldArray = ['o1' => [], 'o2' => [], 'o3' => [], 'o4' => [], 'o5' => [], 'o6' => [], 'o7' => []];
foreach(\$newArray as \$key=>\$item){
\$array1 = array_slice(\$oldArray, 0, \$item['fixed']-1);
\$array2 = array_slice(\$oldArray, \$item['fixed']-1);
\$oldArray = array_merge(\$array1, array(\$key=>\$item), \$array2);
}
//\$oldArray就是你要的结果``````