array_splice() 表示关联数组

2022-08-30 10:26:36

假设我有一个关联数组:

array(
  "color" => "red",
  "taste" => "sweet",
  "season" => "summer"
);

我想在其中引入一个新元素:

"texture" => "bumpy" 

在第二项后面,但保留所有数组键:

array(
  "color" => "red",
  "taste" => "sweet",
  "texture" => "bumpy", 
  "season" => "summer"
);

有没有一个功能可以做到这一点?array_splice() 不会剪切它,它只能使用数字键。


答案 1

我认为您需要手动执行此操作:

# Insert at offset 2
$offset = 2;
$newArray = array_slice($oldArray, 0, $offset, true) +
            array('texture' => 'bumpy') +
            array_slice($oldArray, $offset, NULL, true);

答案 2

基于soulmerge的答案,我创建了这个方便的函数:

function array_insert($array,$values,$offset) {
    return array_slice($array, 0, $offset, true) + $values + array_slice($array, $offset, NULL, true);  
}