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

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


你可能会发现这更直观一些。 它只需要对array_splice一次函数调用:

$original = array( 'a', 'b', 'c', 'd', 'e' );
$inserted = array( 'x' ); // Not necessarily an array

array_splice( $original, 3, 0, $inserted ); // splice in at position 3
// $original is now a b c x d e

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

/**
 * @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',
  ),
)

$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)
链接地址: http://www.djcxy.com/p/58937.html

上一篇: Insert new item in array on any position in PHP

下一篇: if $a and $b are bothe arrays the what would be the result of $a+$b?