array_splice() 用于关联数组 [英] array_splice() for associative arrays

查看:43
本文介绍了array_splice() 用于关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个关联数组:

Say I have an associative array:

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

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

and I want to introduce a new element into it:

"texture" => "bumpy" 

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

behind the 2nd item but preserving all the array keys:

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

有什么功能可以做到这一点吗?array_splice() 不会剪,只能用数字键.

is there a function to do that? array_splice() won't cut it, it can work with numeric keys only.

推荐答案

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

I think you need to do that manually:

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

这篇关于array_splice() 用于关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆