例如,假设我有
$input = array(0, 1, 2, 3, 4, 5, 6, 7);
Run Code Online (Sandbox Code Playgroud)
如何删除元素5并插入位置2,留下我
0,1,5,2,3,4,6,7
$input = array(0, 1, 2, 3, 4, 5, 6, 7);
array_splice($input, 2, 0, array($input[5])); //Place the a new array in the 3rd place of array
unset($input[6]); //remove the fifth element
array_splice($input, 0, 0); //to update the indexes
echo "<pre>".print_r($input,1)."</pre>"; //to view the array
Run Code Online (Sandbox Code Playgroud)
方法无需取消设置和重新排列索引
$input = array(0, 1, 2, 3, 4, 5, 6, 7);
array_splice($input, 2, 0, array_splice($input,5,1));
Run Code Online (Sandbox Code Playgroud)
产量
Array
(
[0] => 0
[1] => 1
[2] => 5
[3] => 2
[4] => 4
[5] => 5
[6] => 6
[7] => 7
)
Run Code Online (Sandbox Code Playgroud)