0

比如说,

两个数组$newArray和$oldArray;

//去插入的数组
$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是我们最终想要的数组;

有什么好的方法能实现这个需求呢?


clipboard.png

上面的两个数组可能有点不太具体,这个是这里真实打印出来的两个数组;

上面这个是要去插入的数组,根据fixed字段去固定位置;

下面这个数组是根据我们自己的排序算法拿到的数组;(被插入的数组);

2019-05-18 提问
2 个回答
1
<?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就是你要的结果
0

直接 foreach/for $res 索引数组可直接设置

<?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);

撰写答案

推广链接