问题描述
如何将新项目插入到数组的任意位置,例如在数组的中间?
您可能会发现这更直观一些.它只需要一个函数调用 array_splice:
$original = array('a', 'b', 'c', 'd', 'e' );$inserted = array('x');//不一定是数组,见手册引用array_splice($original, 3, 0, $inserted);//在位置 3 处拼接//$original 现在是 a b c x d e
<块引用>
如果替换只是一个元素,则无需在其周围放置 array(),除非该元素是数组本身、对象或 NULL.
<块引用>
返回值:需要注意的是,该函数不返回所需的替换.$original
通过引用传递并就地编辑.在 array &$array 和 &
splice.php" rel="nofollow noreferrer">参数列表
.
How can I insert a new item into an array on any position, for example in the middle of array?
You may find this a little more intuitive. It only requires one function call to array_splice
:
$original = array( 'a', 'b', 'c', 'd', 'e' );
$inserted = array( 'x' ); // not necessarily an array, see manual quote
array_splice( $original, 3, 0, $inserted ); // splice in at position 3
// $original is now a b c x d e
If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL.
RETURN VALUE: To be noted that the function does not return the desired substitution. The
$original
is passed by reference and edited in place. See the expressionarray &$array
with&
in theparameters list
.
这篇关于在 PHP 中的任意位置插入数组中的新项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!