如何将一个新项目插入到数组的任何位置,例如在数组的中间?
当前回答
在做了几天之后,这是我能找到的最简单的解决方案。
$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.
其他回答
基于@Halil的伟大回答,这里是一个简单的函数如何在特定的键后插入新元素, 同时保留整型键:
private function arrayInsertAfterKey($array, $afterKey, $key, $value){
$pos = array_search($afterKey, array_keys($array));
return array_merge(
array_slice($array, 0, $pos, $preserve_keys = true),
array($key=>$value),
array_slice($array, $pos, $preserve_keys = true)
);
}
通常,使用标量值:
$elements = array('foo', ...);
array_splice($array, $position, $length, $elements);
要在数组中插入一个数组元素,不要忘记将数组包装在数组中(因为它是一个标量值!):
$element = array('key1'=>'value1');
$elements = array($element);
array_splice($array, $position, $length, $elements);
否则,数组的所有键都将逐条添加。
这个由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; }
函数来源-这篇博文。还有一个方便的功能,以插入之前特定的关键。
这可以通过array_splice完成,但是,当插入数组或使用字符串键时,array_splice会失败。我写了一个函数来处理所有情况:
function array_insert(&$arr, $index, $val)
{
if (is_string($index))
$index = array_search($index, array_keys($arr));
if (is_array($val))
array_splice($arr, $index, 0, [$index => $val]);
else
array_splice($arr, $index, 0, $val);
}
你可以用这个
foreach ($array as $key => $value)
{
if($key==1)
{
$new_array[]=$other_array;
}
$new_array[]=$value;
}