如何将一个新项目插入到数组的任何位置,例如在数组的中间?
当前回答
在数组开头添加元素的提示:
$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
其他回答
在做了几天之后,这是我能找到的最简单的解决方案。
$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.
在数组开头添加元素的提示:
$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
你可能会觉得这更直观一些。它只需要调用array_splice一个函数:
$original = array( 'a', 'b', 'c', 'd', 'e' );
$inserted = array( 'x' ); // not necessarily an array, see manual quote
array_splice( $original, 3, 0, $inserted ); // splice in at position 3
// $original is now a b c x d e
如果replacement只是一个元素,则没有必要在它周围加上array(),除非该元素本身是数组、对象或NULL。
RETURN VALUE:需要注意的是,函数不返回所需的替换。$original通过引用传递,并在适当的位置进行编辑。请参阅参数列表中带有&的表达式array &$array。
这个由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; }
函数来源-这篇博文。还有一个方便的功能,以插入之前特定的关键。
基于@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)
);
}