【问题标题】:How to push array elemnt to specific position in another array using php如何使用php将数组元素推送到另一个数组中的特定位置
【发布时间】:2020-05-12 12:01:36
【问题描述】:

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

【问题讨论】:

  • 与单个值的方法基本相同,只需循环第二个数组,然后将值插入到任何你想要的地方
  • 你是怎么知道位置的?
  • @TsaiKoga array_1 是最终数组,所以我需要通过推送新项目特定位置来打印一些值

标签: php arrays array-push array-splice


【解决方案1】:

您需要将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

【讨论】:

  • Singh 感谢您的努力 答案完全符合预期,我从没想过 array_combine 我只是使用 array_splice。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-22
  • 1970-01-01
  • 2014-04-16
  • 2012-02-03
  • 2019-12-04
  • 1970-01-01
  • 2011-07-15
相关资源
最近更新 更多