php数组如何插入到指定位置?
数组示例:
$arr = array(
'tt' => 1333,
'cc' => 333,
'aaz' => 2333,
'ee' => 78,
)
/*
插入一个【 键 'bb' 值 123】到tt后边得 $arr
Array
(
[tt] => 1333
[bb] => 123
[cc] => 333
[aaz] => 2333
[ee] => 78
)
*/
解决方案:
用自带的array_splice无法自定义键值,只能默认用数字索引,用下面的方法简单封装可以实现你的要求
function array_insert (&$array, $position, $insert_array) {
$first_array = array_splice ($array, 0, $position);
$array = array_merge ($first_array, $insert_array, $array);
}
$arr = array(
'tt' => 1333,
'cc' => 333,
'aaz' => 2333,
'ee' => 78,
);
$temp["bb"] = 33;
array_insert($arr,1,$temp);
var_dump($arr);