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

kus*_*agi 457 php arrays insert

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

jay*_*lee 848

您可能会发现这更直观一些.它只需要一个函数调用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
Run Code Online (Sandbox Code Playgroud)

如果替换只是一个元素,则不必在其周围放置array(),除非该元素本身就是一个对象或NULL.

  • 奇怪的是,这样的基本功能实际上是隐藏的,因为文档中描述的这个函数的主要目的是不同的(替换数组中的东西).是的,它在参数部分中指出,但是如果您只是扫描函数描述以找到要在数组中插入的内容,那么您将永远不会找到它. (26认同)
  • 只是说这不会保留`$ inserted`数组中的键. (20认同)
  • 另外在PHP手册中,示例#1:http://php.net/manual/en/function.array-splice.php (5认同)
  • 这不适用于多维数组. (3认同)
  • @SunilPachlangia、adelval 和其他人:对于多维数组,您需要将替换包装在一个数组中,它已记录在案。我仍然把纸条带到这里,所以人们不要再犯这个错误了。 (3认同)
  • @SunilPachlangia 对于多维数组,这个函数允许我在指定位置插入一个数组:https://gist.github.com/wpscholar/0deadce1bbfa4adb4e4c 看起来和这个页面上的其他函数类似,但我发现它更容易理解. (3认同)
  • @JacerOmri是完全正确的,这两个语句都有效。您可以传递任何类型的值,但对于数组,对象或null而言,它的行为可能不同。对于标量,类型转换`(array)$ scalar`等效于`array($ scalar)`,但是对于数组,对象或null,它将被忽略(数组),转换为数组(对象) ,或变成一个空数组(空)-参见http://php.net/manual/zh/language.types.array.php#language.types.array.casting (2认同)

Hal*_*gür 45

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

/**
 * @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)
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

整数用法:

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

字符串用法:

$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',
  ),
)
Run Code Online (Sandbox Code Playgroud)

  • int和string位置的绝佳解决方案:) (2认同)
  • `array_splice()` 会丢失密钥,而 `array_merge()` 不会。所以第一个函数的结果可能会非常令人惊讶......特别是因为如果你有两个具有相同键的元素,那么只保留最后一个的值...... (2认同)

Amb*_*ber 29

$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)
Run Code Online (Sandbox Code Playgroud)

  • 使用`+`而不是`array_merge`可以保存键 (8认同)

小智 7

没有本机 PHP 函数(我知道)可以完全满足您的要求。

我编写了两种我认为适合的方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

虽然速度更快,而且可能内存效率更高,但这仅适用于不需要维护数组键的情况。

如果您确实需要维护密钥,以下方法更合适;

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这工作正常。然而,在第二个例子中,在你的函数 `insertBefore()` 中,你应该返回 `$tmpArray` 而不是 `$input`。 (3认同)

May*_*a M 6

如果要保留初始数组的键并添加具有键的数组,请使用以下函数:

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);
}
Run Code Online (Sandbox Code Playgroud)

调用示例:

$array = insertArrayAtPosition($array, array('key' => 'Value'), 3);
Run Code Online (Sandbox Code Playgroud)


Oks*_*niv 6

Brad Erickson 的这个函数对我来说适用于关联数组:

/*
 * 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;
}
Run Code Online (Sandbox Code Playgroud)

函数来源 -这篇博文。还有一个方便的功能可以在特定键之前插入。


wit*_*ich 6

如何使用保存数组键array_splice()

@jay.lee的答案是正确的,不幸的是它没有保留 an 的键,正如评论array中指出的:

$original = array( 
    'a' => 'A', 
    'b' => 'B', 
    'c' => 'C', 
    // insert here
    'd' => 'D', 
    'e' => 'E');

$inserted = array( 'x' => 'X' ); 

array_splice( $original, 3, 0, $inserted );
print_r($original);

/* Output
Array
(
    [a] => A
    [b] => B
    [c] => C
    [0] => X  <= the lost key 
    [d] => D
    [e] => E
) */
Run Code Online (Sandbox Code Playgroud)

我发现保留数组键的最简单方法是使用该array_splice()函数并使用 / union 运算符将数组添加在一起(在另一个答案的评论+中也提到):

$original = array( 
    'a' => 'A', 
    'b' => 'B', 
    'c' => 'C', 
    // insert here
    'd' => 'D', 
    'e' => 'E');

$inserted = array( 'x' => 'X' ); 

// Insert before postion 'd'
$before = array_splice( $original, 0, 3 ); // $original contains the left over

// Merge together
$result = $before + $inserted + $original;
print_r($result);

/* Output
Array
(
    [a] => A
    [b] => B
    [c] => C
    [x] => X
    [d] => D
    [e] => E
) */
Run Code Online (Sandbox Code Playgroud)

注意:仅在处理非数字键时使用数组联合运算符才是安全的


感谢您的更正@mickmackusa


Ale*_*kov 5

这样,您可以插入数组:

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

  • 该函数不会将订单保存在数组中。 (2认同)

小智 5

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;
}
Run Code Online (Sandbox Code Playgroud)


d.r*_*aev 5

基于@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)
    );
} 
Run Code Online (Sandbox Code Playgroud)