如何使用 php 将数组元素推送到另一个数组中的特定位置
How to push array elemnt to specific position in another array using php
我想将新数组推送到特定位置的另一个数组,为此我使用了 array_splice 遵循了一些 Whosebug 链接,但它对我不起作用
我也引用了这个链接,但他们只提到了单个值而不是数组。
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_1
中的 $array_2
值推送到某个位置,例如:
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);
我想将新数组推送到特定位置的另一个数组,为此我使用了 array_splice 遵循了一些 Whosebug 链接,但它对我不起作用
我也引用了这个链接,但他们只提到了单个值而不是数组。
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_1
中的 $array_2
值推送到某个位置,例如:
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);