PHP 数组在索引处推送元素并移动前一个元素


php array push element at an index and move the previous element

这是我的数组。我想在索引 3 处推送一个元素,同时将前一个元素移动到下一个元素。请先阅读它不是array_splice()工作

array(6) {
  [0]=>
  string(1) "One_test"
  [1]=>
  string(1) "Two_test"
  [2]=>
  string(1) "Three_test"
  [3]=>
  string(1) "Four_test"
  [4]=>
  string(1) "Five_test"
  [5]=>
  string(1) "Six_test"
}

所以我想要的输出是

array(6) {
  [0]=>
  string(1) "One_test"
  [1]=>
  string(1) "Two_test"
  [2]=>
  string(1) "Three_test"
  [3]=>
  string(1) "Six_test"
  [4]=>
  string(1) "Four_test"
  [5]=>
  string(1) "Five_test"
}

因此,请注意,我需要3rd索引元素替换为索引元素5th然后将先前3rd索引元素移动到下一个。最后将推送的元素(第 5 个)删除

知道吗?

灵感来自欺骗:在 PHP 中的任何位置插入数组中的新项目

我会在数组上做一个array_pop()array_slice()

$original = array( 'a', 'b', 'c', 'd', 'e' );
$new_one = array_pop($original);
array_splice( $original, 3, 0, $new_one );

我的解决方案

所以之前:

array(6) {
  [0]=>
  string(8) "One_test"
  [1]=>
  string(8) "Two_test"
  [2]=>
  string(10) "Three_test"
  [3]=>
  string(9) "Four_test"
  [4]=>
  string(9) "Five_test"
  [5]=>
  string(8) "Six_test"
}

之后:

array(6) {
  [0]=>
  string(8) "One_test"
  [1]=>
  string(8) "Two_test"
  [2]=>
  string(10) "Three_test"
  [3]=>
  string(8) "Six_test"
  [4]=>
  string(9) "Four_test"
  [5]=>
  string(9) "Five_test"
}

此方法获取数组、要移动的项的索引以及要将项推送到的索引。

function moveArrayItem($array, $currentPosition, $newPosition){
    //get value of index you want to move
    $val = array($array[$currentPosition]);
    //remove item from array
    $array = array_diff($array, $val);
    //push item into new position
    array_splice($array,$newPosition,0,$val);
    return $array;
}

使用示例:

$a = array("first", "second", "third", "fourth", "fifth", "sixth");
$newArray = moveArrayItem($a, 5, 3);