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

查看:23
本文介绍了在 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.

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.

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

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