在 PHP 中的任意位置插入数组中的新项目

2022-01-09 00:00:00 arrays insert php

如何将新项目插入到数组的任意位置,例如在数组的中间?

解决方案

您可能会发现这更直观一些.它只需要一个函数调用 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 expression array &$array with & in the parameters list .

相关文章