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

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

513289 次浏览
$a = array(1, 2, 3, 4);
$b = array_merge(array_slice($a, 0, 2), array(5), array_slice($a, 2));
// $b = array(1, 2, 5, 3, 4)

你可能会觉得这更直观一些。它只需要一个函数调用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

如果replacement只是一个元素,则没有必要在它周围加上array(),除非该元素本身是数组、对象或NULL。

RETURN VALUE:需要注意的是,函数返回所需的替换。$original通过引用传递,并在适当位置进行编辑。参见表达式array &$array&parameters list中。

要将元素插入到具有字符串键的数组中,您可以这样做:

/* insert an element after given array key
* $src = array()  array to work with
* $ins = array() to insert in key=>array format
* $pos = key that $ins will be inserted after
*/
function array_insert_string_keys($src,$ins,$pos) {


$counter=1;
foreach($src as $key=>$s){
if($key==$pos){
break;
}
$counter++;
}


$array_head = array_slice($src,0,$counter);
$array_tail = array_slice($src,$counter);


$src = array_merge($array_head, $ins);
$src = array_merge($src, $array_tail);


return($src);
}

这样你就可以插入数组:

function array_insert(&$array, $value, $index)
{
return $array = array_merge(array_splice($array, max(0, $index - 1)), array($value), $array);
}

通常,使用标量值:

$elements = array('foo', ...);
array_splice($array, $position, $length, $elements);

要在数组中插入一个数组元素,不要忘记将数组包装在数组中(因为它是一个标量值!):

$element = array('key1'=>'value1');
$elements = array($element);
array_splice($array, $position, $length, $elements);

否则,数组的所有键都将逐条添加。

function insert(&$arr, $value, $index){
$lengh = count($arr);
if($index<0||$index>$lengh)
return;


for($i=$lengh; $i>$index; $i--){
$arr[$i] = $arr[$i-1];
}


$arr[$index] = $value;
}

添加元素在数组的开头的提示:

$a = array('first', 'second');
$a[-1] = 'i am the new first element';

然后:

foreach($a as $aelem)
echo $a . ' ';
//returns first, second, i am...

但是:

for ($i = -1; $i < count($a)-1; $i++)
echo $a . ' ';
//returns i am as 1st element

没有本地PHP函数(据我所知)可以完全完成您的请求。

我已经写了2个我认为适合目的的方法:

function insertBefore($input, $index, $element) {
if (!array_key_exists($index, $input)) {
throw new Exception("Index not found");
}
$tmpArray = array();
$originalIndex = 0;
foreach ($input as $key => $value) {
if ($key === $index) {
$tmpArray[] = $element;
break;
}
$tmpArray[$key] = $value;
$originalIndex++;
}
array_splice($input, 0, $originalIndex, $tmpArray);
return $input;
}


function insertAfter($input, $index, $element) {
if (!array_key_exists($index, $input)) {
throw new Exception("Index not found");
}
$tmpArray = array();
$originalIndex = 0;
foreach ($input as $key => $value) {
$tmpArray[$key] = $value;
$originalIndex++;
if ($key === $index) {
$tmpArray[] = $element;
break;
}
}
array_splice($input, 0, $originalIndex, $tmpArray);
return $input;
}

虽然速度更快,而且可能更节省内存,但这只适用于不需要维护数组键的地方。

如果你确实需要维护密钥,下面的方法会更合适;

function insertBefore($input, $index, $newKey, $element) {
if (!array_key_exists($index, $input)) {
throw new Exception("Index not found");
}
$tmpArray = array();
foreach ($input as $key => $value) {
if ($key === $index) {
$tmpArray[$newKey] = $element;
}
$tmpArray[$key] = $value;
}
return $input;
}


function insertAfter($input, $index, $newKey, $element) {
if (!array_key_exists($index, $input)) {
throw new Exception("Index not found");
}
$tmpArray = array();
foreach ($input as $key => $value) {
$tmpArray[$key] = $value;
if ($key === $index) {
$tmpArray[$newKey] = $element;
}
}
return $tmpArray;
}

可以在整数和字符串位置进行插入的函数:

/**
* @param array      $array
* @param int|string $position
* @param mixed      $insert
*/
function array_insert(&$array, $position, $insert)
{
if (is_int($position)) {
array_splice($array, $position, 0, $insert);
} else {
$pos   = array_search($position, array_keys($array));
$array = array_merge(
array_slice($array, 0, $pos),
$insert,
array_slice($array, $pos)
);
}
}

整数的用法:

$arr = ["one", "two", "three"];
array_insert(
$arr,
1,
"one-half"
);
// ->
array (
0 => 'one',
1 => 'one-half',
2 => 'two',
3 => 'three',
)

字符串的用法:

$arr = [
"name"  => [
"type"      => "string",
"maxlength" => "30",
],
"email" => [
"type"      => "email",
"maxlength" => "150",
],
];


array_insert(
$arr,
"email",
[
"phone" => [
"type"   => "string",
"format" => "phone",
],
]
);
// ->
array (
'name' =>
array (
'type' => 'string',
'maxlength' => '30',
),
'phone' =>
array (
'type' => 'string',
'format' => 'phone',
),
'email' =>
array (
'type' => 'email',
'maxlength' => '150',
),
)

这也是一个有效的解决方案:

function array_insert(&$array,$element,$position=null) {
if (count($array) == 0) {
$array[] = $element;
}
elseif (is_numeric($position) && $position < 0) {
if((count($array)+position) < 0) {
$array = array_insert($array,$element,0);
}
else {
$array[count($array)+$position] = $element;
}
}
elseif (is_numeric($position) && isset($array[$position])) {
$part1 = array_slice($array,0,$position,true);
$part2 = array_slice($array,$position,null,true);
$array = array_merge($part1,array($position=>$element),$part2);
foreach($array as $key=>$item) {
if (is_null($item)) {
unset($array[$key]);
}
}
}
elseif (is_null($position)) {
$array[] = $element;
}
elseif (!isset($array[$position])) {
$array[$position] = $element;
}
$array = array_merge($array);
return $array;
}

学分去: # EYZ0 < / p >

基于@Halil伟大的回答,这里是一个简单的函数如何在特定的键后插入新元素, 当保留整型键时:

private function arrayInsertAfterKey($array, $afterKey, $key, $value){
$pos   = array_search($afterKey, array_keys($array));


return array_merge(
array_slice($array, 0, $pos, $preserve_keys = true),
array($key=>$value),
array_slice($array, $pos, $preserve_keys = true)
);
}

如果不确定,那么不要使用这些:

$arr1 = $arr1 + $arr2;

$arr1 += $arr2;

因为使用+原始数组将被覆盖。(# EYZ1)

试试这个:

$colors = array('red', 'blue', 'yellow');


$colors = insertElementToArray($colors, 'green', 2);




function insertElementToArray($arr = array(), $element = null, $index = 0)
{
if ($element == null) {
return $arr;
}


$arrLength = count($arr);
$j = $arrLength - 1;


while ($j >= $index) {
$arr[$j+1] = $arr[$j];
$j--;
}


$arr[$index] = $element;


return $arr;
}

杰伊的解决方案。李是完美的。如果要向多维数组中添加项,请先添加一个一维数组,然后再替换它。

$original = (
[0] => Array
(
[title] => Speed
[width] => 14
)


[1] => Array
(
[title] => Date
[width] => 18
)


[2] => Array
(
[title] => Pineapple
[width] => 30
)
)

将相同格式的项添加到此数组中将添加所有新的数组索引作为项,而不仅仅是项。

$new = array(
'title' => 'Time',
'width' => 10
);
array_splice($original,1,0,array('random_string')); // can be more items
$original[1] = $new;  // replaced with actual item

直接向使用作用是的多维数组添加项将把它的所有索引作为项添加,而不仅仅是该项。

你可以用这个

foreach ($array as $key => $value)
{
if($key==1)
{
$new_array[]=$other_array;
}
$new_array[]=$value;
}

如果你想保留初始数组的键,并添加一个有键的数组,那么使用下面的函数:

function insertArrayAtPosition( $array, $insert, $position ) {
/*
$array : The initial array i want to modify
$insert : the new array i want to add, eg array('key' => 'value') or array('value')
$position : the position where the new array will be inserted into. Please mind that arrays start at 0
*/
return array_slice($array, 0, $position, TRUE) + $insert + array_slice($array, $position, NULL, TRUE);
}

电话的例子:

$array = insertArrayAtPosition($array, array('key' => 'Value'), 3);

这是为我工作的关联数组:

/*
* Inserts a new key/value after the key in the array.
*
* @param $key
*   The key to insert after.
* @param $array
*   An array to insert in to.
* @param $new_key
*   The key to insert.
* @param $new_value
*   An value to insert.
*
* @return
*   The new array if the key exists, FALSE otherwise.
*
* @see array_insert_before()
*/
function array_insert_after($key, array &$array, $new_key, $new_value) {
if (array_key_exists($key, $array)) {
$new = array();
foreach ($array as $k => $value) {
$new[$k] = $value;
if ($k === $key) {
$new[$new_key] = $new_value;
}
}
return $new;
}
return FALSE;
}

函数source - 这篇博文。还有一个方便的功能,以插入之前特定的关键。

function array_insert($array, $position, $insert) {
if ($position > 0) {
if ($position == 1) {
array_unshift($array, array());
} else {
$position = $position - 1;
array_splice($array, $position, 0, array(
''
));
}
$array[$position] = $insert;
}


return $array;
}

电话的例子:

$array = array_insert($array, 1, ['123', 'abc']);

这可以使用array_splice完成,但是,当插入数组或使用字符串键时,array_splice会失败。我写了一个函数来处理所有情况:

function array_insert(&$arr, $index, $val)
{
if (is_string($index))
$index = array_search($index, array_keys($arr));
if (is_array($val))
array_splice($arr, $index, 0, [$index => $val]);
else
array_splice($arr, $index, 0, $val);
}

你可以试试,用这个方法让它变得简单

/**
* array insert element on position
*
* @link https://vector.cool
*
* @since 1.01.38
*
* @param array $original
* @param mixed $inserted
* @param int   $position
* @return array
*/
function array_insert(&$original, $inserted, int $position): array
{
array_splice($original, $position, 0, array($inserted));
return $original;
}




$columns = [
['name' => '預約項目', 'column' => 'item_name'],
['name' => '預約時間', 'column' => 'start_time'],
['name' => '預約姓名', 'column' => 'full_name'],
['name' => '連絡電話', 'column' => 'phone'],
['name' => '建立時間', 'column' => 'create_time']
];
$col = ['name' => '預約帳戶', 'column' => 'user_id'];
$columns = array_insert($columns, $col, 3);
print_r($columns);

打印:

Array
(
[0] => Array
(
[name] => 預約項目
[column] => item_name
)
[1] => Array
(
[name] => 預約時間
[column] => start_time
)
[2] => Array
(
[name] => 預約姓名
[column] => full_name
)
[3] => Array
(
[name] => 報名人數1
[column] => num_of_people
)
[4] => Array
(
[name] => 連絡電話
[column] => phone
)
[5] => Array
(
[name] => 預約帳戶
[column] => user_id
)
[6] => Array
(
[name] => 建立時間
[column] => create_time
)
)

如果你有正则数组,没有什么特别的,这就可以了。记住,使用array_splice()插入元素实际上意味着插入到开始索引之前。移动元素时要小心,因为向上移动意味着$targetIndex -1,向下移动意味着$targetIndex + 1。

class someArrayClass
{
private const KEEP_EXISTING_ELEMENTS = 0;


public function insertAfter(array $array, int $startIndex, $newElements)
{
return $this->insertBefore($array, $startIndex + 1, $newElements);
}


public function insertBefore(array $array, int $startIndex, $newElements)
{
return array_splice($array, $startIndex, self::KEEP_EXISTING_ELEMENTS, $newElements);
}
}
$result_array = array();
$array = array("Tim","John","Mark");
$new_element = "Bill";
$position = 1;


for ($i=0; $i<count($array); $i++)
{
if ($i==$position)
{
$result_array[] = $new_element;
}
$result_array[] = $array[$i];
}


print_r($result_array);


// Result will Array([0] => "Tim",[1] => "Bill", [2] => "John",[1] => "Mark")

在做了几天之后,这是我能找到的最简单的解决方案。

$indexnumbertoaddat // this is a variable that points to the index # where you
want the new array to be inserted


$arrayToAdd = array(array('key' => $value, 'key' => $value)); //this is the new
array and it's values that you want to add. //the key here is to write it like
array(array('key' =>, since you're adding this array inside another array. This
is the point that a lot of answer left out.


array_splice($originalArray, $indexnumbertoaddatt, 0, $arrayToAdd); //the actual
splice function. You're doing it to $originalArray, at the index # you define,
0 means you're just shifting all other index items down 1, and then you add the
new array.