php 在指定位置插入数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1763959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert into array at a specified place
提问by Gal
array:
大批:
A-B-C-D-E-F
J is the son of C. update array so:
J 是 C 的儿子。更新数组所以:
A-B-C-J-D-E-F
how do I insert J after C in the array?
如何在数组中的 C 之后插入 J?
I also map the array in a loop (array of comments for display). Will this method take a very long time to perform?
我还在循环中映射数组(用于显示的注释数组)。这种方法需要很长时间才能执行吗?
回答by Pekka
You can use array_splice() with $length set to 0.
您可以使用 $length 设置为 0 的 array_splice()。
http://de.php.net/manual/en/function.array-splice.php
http://de.php.net/manual/en/function.array-splice.php
Example:
例子:
$arr_alphabet = array('a', 'b', 'd');
array_splice($arr_alphabet, 2, 0, 'c');
// $arr_alphabet is now: array('a', 'b', 'c', 'd');
回答by Ben Fransen
Use the splice function to solve this.
使用 splice 功能来解决这个问题。
回答by Kevin Howard Goldberg
For those who run into problems ... I found that @Pekka's solution ended up returning a NULL array because array_splice returns the array consisting of the extracted elements (http://de.php.net/manual/en/function.array-splice.php).
对于那些遇到问题的人......我发现@Pekka 的解决方案最终返回一个 NULL 数组,因为 array_splice 返回由提取元素组成的数组(http://de.php.net/manual/en/function.array- splice.php)。
It would be more accurate as follows:
它会更准确如下:
$arr_alphabet = array('a', 'b', 'd');
array_splice($arr_alphabet, 2, 0, 'c');
print_r($arr_alphabet);
Returns:
返回:
Array ( [0] => a [1] => b [2] => c [3] => d )
But thanks @Pekka for getting me 95% of the way there!
但是感谢@Pekka 让我完成了 95% 的旅程!

