假设我们有两个数组:
$array_1 = array(
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'3' => 'three',
);
$array_2 = array(
'zero' => '0',
'one' => '1',
'two' => '2',
'three' => '3',
);
现在,我想在每个数组的第三个元素后插入数组('sample_key' => 'sample_value')。我该怎么做呢?
非常简单的2个字符串回答你的问题:
$array_1 = array(
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'3' => 'three',
);
首先,你用array_splice向第三个元素插入任何东西,然后给这个元素赋值:
array_splice($array_1, 3, 0 , true);
$array_1[3] = array('sample_key' => 'sample_value');
这是一种更好的方法,如何在数组的某个位置插入项目。
function arrayInsert($array, $item, $position)
{
$begin = array_slice($array, 0, $position);
array_push($begin, $item);
$end = array_slice($array, $position);
$resultArray = array_merge($begin, $end);
return $resultArray;
}
如果你不知道你想在位置3插入它,但你知道你想在后面插入它的键,在看到这个问题后,我想出了这个小函数。
/**
* Inserts any number of scalars or arrays at the point
* in the haystack immediately after the search key ($needle) was found,
* or at the end if the needle is not found or not supplied.
* Modifies $haystack in place.
* @param array &$haystack the associative array to search. This will be modified by the function
* @param string $needle the key to search for
* @param mixed $stuff one or more arrays or scalars to be inserted into $haystack
* @return int the index at which $needle was found
*/
function array_insert_after(&$haystack, $needle = '', $stuff){
if (! is_array($haystack) ) return $haystack;
$new_array = array();
for ($i = 2; $i < func_num_args(); ++$i){
$arg = func_get_arg($i);
if (is_array($arg)) $new_array = array_merge($new_array, $arg);
else $new_array[] = $arg;
}
$i = 0;
foreach($haystack as $key => $value){
++$i;
if ($key == $needle) break;
}
$haystack = array_merge(array_slice($haystack, 0, $i, true), $new_array, array_slice($haystack, $i, null, true));
return $i;
}
这里是一个代码板小提琴看到它的行动:http://codepad.org/5WlKFKfz
注意:array_splice()会比array_merge(array_slice())更有效,但这样你插入的数组的键就会丢失。叹息。
我最近写了一个函数来做一些类似于你正在尝试的事情,这与clasvdb的答案类似。
function magic_insert($index,$value,$input_array ) {
if (isset($input_array[$index])) {
$output_array = array($index=>$value);
foreach($input_array as $k=>$v) {
if ($k<$index) {
$output_array[$k] = $v;
} else {
if (isset($output_array[$k]) ) {
$output_array[$k+1] = $v;
} else {
$output_array[$k] = $v;
}
}
}
} else {
$output_array = $input_array;
$output_array[$index] = $value;
}
ksort($output_array);
return $output_array;
}
基本上,它在一个特定的点插入,但通过向下移动所有项来避免覆盖。