"red", "taste" => "sweet", "season" => "summer" ); 我想在其中引入一个新元素:-6ren">
gpt4 book ai didi

php - array_splice() 用于关联数组

转载 作者:IT王子 更新时间:2023-10-29 00:51:40 24 4
gpt4 key购买 nike

假设我有一个关联数组:

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

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

"texture" => "bumpy" 

在第二个项目之后,但保留所有数组键:

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

有这样的功能吗? array_splice()不会削减它,它只能与数字键一起使用。

最佳答案

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

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

关于php - array_splice() 用于关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1783089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com