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


当前回答

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

@jay的答案。Lee是正确的,不幸的是,它不能保存数组的键,正如评论中指出的那样:

$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
) */

我发现保存数组键的最简单的方法是使用array_splice()函数,并使用+ /联合操作符将数组添加在一起(也在另一个答案的评论中提到):

$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
) */

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


谢谢你的更正@mickmackusa

其他回答

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

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;
}

获奖者: http://binarykitten.com/php/52-php-insert-element-and-shift.html

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

/**
 * @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, $value, $index)
{
    return $array = array_merge(array_splice($array, max(0, $index - 1)), array($value), $array);
}

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

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

然后:

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

but:

for ($i = -1; $i < count($a)-1; $i++)
     echo $a . ' ';
//returns i am as 1st element
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']);