这是我的阵列。我想在索引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
索引元素移到下一个中。最后推送元素(5th)去除
任何想法?
答案 0 :(得分:2)
受到欺骗的启发:Insert new item in array on any position in 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"
}
答案 1 :(得分:0)
此方法获取数组,要移动的项目的索引以及要将项目推送到的索引。
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);