如何将一个新项目插入到数组的任何位置,例如在数组的中间?
当前回答
你可以用这个
foreach ($array as $key => $value)
{
if($key==1)
{
$new_array[]=$other_array;
}
$new_array[]=$value;
}
其他回答
试试这个:
$colors = array('red', 'blue', 'yellow');
$colors = insertElementToArray($colors, 'green', 2);
function insertElementToArray($arr = array(), $element = null, $index = 0)
{
if ($element == null) {
return $arr;
}
$arrLength = count($arr);
$j = $arrLength - 1;
while ($j >= $index) {
$arr[$j+1] = $arr[$j];
$j--;
}
$arr[$index] = $element;
return $arr;
}
你可以用这个
foreach ($array as $key => $value)
{
if($key==1)
{
$new_array[]=$other_array;
}
$new_array[]=$value;
}
如何使用array_splice()保存数组键
@jay的答案。Lee是正确的,不幸的是,它不能保存数组的键,正如评论中指出的那样:
$original = array(
'a' => 'A',
'b' => 'B',
'c' => 'C',
// insert here
'd' => 'D',
'e' => 'E');
$inserted = array( 'x' => 'X' );
array_splice( $original, 3, 0, $inserted );
print_r($original);
/* Output
Array
(
[a] => A
[b] => B
[c] => C
[0] => X <= the lost key
[d] => D
[e] => E
) */
我发现保存数组键的最简单的方法是使用array_splice()函数,并使用+ /联合操作符将数组添加在一起(也在另一个答案的评论中提到):
$original = array(
'a' => 'A',
'b' => 'B',
'c' => 'C',
// insert here
'd' => 'D',
'e' => 'E');
$inserted = array( 'x' => 'X' );
// Insert before postion 'd'
$before = array_splice( $original, 0, 3 ); // $original contains the left over
// Merge together
$result = $before + $inserted + $original;
print_r($result);
/* Output
Array
(
[a] => A
[b] => B
[c] => C
[x] => X
[d] => D
[e] => E
) */
注意:使用数组联合操作符仅在处理非数字键时是安全的
谢谢你的更正@mickmackusa
这样你就可以插入数组:
function array_insert(&$array, $value, $index)
{
return $array = array_merge(array_splice($array, max(0, $index - 1)), array($value), $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
推荐文章
- 在PHP单元测试执行期间,如何在CLI中输出?
- 在PHP中使用heredoc的优势是什么?
- PHP中的echo, print和print_r有什么区别?
- 如何在c#中连接列表?
- 在JavaScript中根据键值查找和删除数组中的对象
- 如何确定一个数组是否包含另一个数组的所有元素
- 如何将XML转换成PHP数组?
- 给定一个数字数组,返回所有其他数字的乘积的数组(不除法)
- 多维数组如何在内存中格式化?
- 如何将对象转换为数组?
- 从IP地址获取位置
- 在STL地图中,使用map::insert比[]更好吗?
- TypeScript枚举对象数组
- 获取数组值的键名
- HTTPS和SSL3_GET_SERVER_CERTIFICATE:证书验证失败,CA is OK