在 PHP 中的任意位置插入数组中的新项目 [英] Insert new item in array on any position in PHP

查看:13
本文介绍了在 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 通过引用传递并就地编辑.在 参数列表 .

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 .

这篇关于在 PHP 中的任意位置插入数组中的新项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆