我想将新数组推送到特定位置的另一个数组,为此我使用了 array_splice 并遵循了一些 stackoverflow 链接,但它对我不起作用
我也引用了这个链接,但他们只提到了单个值而不是数组。
How to insert element into arrays at specific position?
Insert new item in array on any position in PHP
Example:
$array_1 = array(1,2,3,4,5);
$array_2 = array(a,b,c);
现在我想将 $array_2
值推送到 $array_1
中的某个位置,例如:
a at position 1
b at position 3
c at position 4
预期输出:
$final_array=(1,a,2,b,c,3,4,5);
最佳答案
您需要将positions
定义为数组并将其与array_2
组合。现在迭代这个组合数组并使用第一个引用线程的代码:
<?php
$array_1 = array(1,2,3,4,5);
$array_2 = array('a','b','c');
//define positions array
$positions = array(1,3,4);
//combine position array with $array_2
$positionArray = array_combine($positions, $array_2);
//iterate over combined array
foreach($positionArray as $key => $value){
//use code of first example thread
array_splice($array_1, $key, 0, $value);
//here $key is position where you want to insert
}
print_r($array_1);
关于php - 如何使用php将数组元素推送到另一个数组中的特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59925586/