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


当前回答

通常,使用标量值:

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

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

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

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

其他回答

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

$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. 

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

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

这个由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; }

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

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一个函数:

$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。