在 PHP 中的任意位置插入数组中的新项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3797239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert new item in array on any position in PHP
提问by kusanagi
How can I insert a new item into an array on any position, for example in the middle of array?
如何将新项目插入到任何位置的数组中,例如在数组的中间?
回答by jay.lee
You may find this a little more intuitive. It only requires one function call to array_splice
:
您可能会发现这更直观一些。它只需要一个函数调用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.
如果替换只是一个元素,则无需在其周围放置 array(),除非该元素是数组本身、对象或 NULL。
回答by Halil ?zgür
A function that can insert at both integer and string positions:
可以在整数和字符串位置插入的函数:
/**
* @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)
);
}
}
Integer usage:
整数用法:
$arr = ["one", "two", "three"];
array_insert(
$arr,
1,
"one-half"
);
// ->
array (
0 => 'one',
1 => 'one-half',
2 => 'two',
3 => 'three',
)
String Usage:
字符串用法:
$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',
),
)
回答by Amber
$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)
回答by Aleksandr Makov
This way you can insert arrays:
这样你就可以插入数组:
function array_insert(&$array, $value, $index)
{
return $array = array_merge(array_splice($array, max(0, $index - 1)), array($value), $array);
}
回答by A Boy Named Su
There is no native PHP function (that I am aware of) that can do exactly what you requested.
没有本机 PHP 函数(我知道)可以完全满足您的要求。
I've written 2 methods that I believe are fit for purpose:
我编写了两种我认为适合的方法:
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;
}
While faster and probably more memory efficient, this is only really suitable where it is not necessary to maintain the keys of the array.
虽然速度更快,而且可能内存效率更高,但这仅适用于不需要维护数组键的情况。
If you do need to maintain keys, the following would be more suitable;
如果您确实需要维护密钥,则以下方法更合适;
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;
}
回答by d.raev
Based on @Halil great answer, here is simple function how to insert new element after a specific key, while preserving integer keys:
基于@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)
);
}
回答by Mayra M
If you want to keep the keys of the initial array and also add an array that has keys, then use the function below:
如果要保留初始数组的键并添加具有键的数组,请使用以下函数:
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);
}
Call example:
调用示例:
$array = insertArrayAtPosition($array, array('key' => 'Value'), 3);
回答by Oksana Romaniv
This is what worked for me for the associative array:
对于关联数组,这对我有用:
/*
* 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;
}
The function source - this blog post. There's also handy function to insert BEFORE specific key.
函数源 -这篇博文。还有一个方便的功能可以在特定键之前插入。
回答by henry wong
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;
}
回答by Abdul Mannan
Solution by jay.lee is perfect. In case you want to add item(s) to a multidimensional array, first add a single dimensional array and then replace it afterwards.
jay.lee 的解决方案是完美的。如果要将项目添加到多维数组,请先添加一维数组,然后再替换它。
$original = (
[0] => Array
(
[title] => Speed
[width] => 14
)
[1] => Array
(
[title] => Date
[width] => 18
)
[2] => Array
(
[title] => Pineapple
[width] => 30
)
)
Adding an item in same format to this array will add all new array indexes as items instead of just item.
将相同格式的项目添加到此数组中会将所有新的数组索引添加为项目,而不仅仅是项目。
$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
Note:Adding items directly to a multidimensional array with array_splicewill add all its indexes as items instead of just that item.
注意:使用array_splice将项目直接添加到多维数组会将其所有索引添加为项目,而不仅仅是该项目。