php - 如何使用php将数组元素推送到另一个数组中的特定位置

标签 php arrays array-push array-splice

我想将新数组推送到特定位置的另一个数组,为此我使用了 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);

输出:https://3v4l.org/Djar2

关于php - 如何使用php将数组元素推送到另一个数组中的特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59925586/

相关文章:

arrays - 使用 Transpose 函数会导致错误

PHP array_push() 正在覆盖现有的数组元素

c - 为什么需要将 NUL 字符附加到数组中?

javascript - JS : How to combine Object from two different arrays into one Array/Object

PHP 将 CSV 文件中的值放入数组中

php - 烦人的查询错误

php - 数组排序键在数字上有帮助

php - laravel 模型获取具有自定义值的数据

php - 如何使用 InnoDB 表加速缓慢的 MySQL UPDATE 查询

javascript - 映射 Json 数组值