如何将一个新项目插入到数组的任何位置,例如在数组的中间?
当前回答
$a = array(1, 2, 3, 4);
$b = array_merge(array_slice($a, 0, 2), array(5), array_slice($a, 2));
// $b = array(1, 2, 5, 3, 4)
其他回答
$a = array(1, 2, 3, 4);
$b = array_merge(array_slice($a, 0, 2), array(5), array_slice($a, 2));
// $b = array(1, 2, 5, 3, 4)
在数组开头添加元素的提示:
$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.
这可以通过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);
}
通常,使用标量值:
$elements = array('foo', ...);
array_splice($array, $position, $length, $elements);
要在数组中插入一个数组元素,不要忘记将数组包装在数组中(因为它是一个标量值!):
$element = array('key1'=>'value1');
$elements = array($element);
array_splice($array, $position, $length, $elements);
否则,数组的所有键都将逐条添加。