如何将一个新项目插入到数组的任何位置,例如在数组的中间?
当前回答
function insert(&$arr, $value, $index){
$lengh = count($arr);
if($index<0||$index>$lengh)
return;
for($i=$lengh; $i>$index; $i--){
$arr[$i] = $arr[$i-1];
}
$arr[$index] = $value;
}
其他回答
要将元素插入到具有字符串键的数组中,您可以这样做:
/* insert an element after given array key
* $src = array() array to work with
* $ins = array() to insert in key=>array format
* $pos = key that $ins will be inserted after
*/
function array_insert_string_keys($src,$ins,$pos) {
$counter=1;
foreach($src as $key=>$s){
if($key==$pos){
break;
}
$counter++;
}
$array_head = array_slice($src,0,$counter);
$array_tail = array_slice($src,$counter);
$src = array_merge($array_head, $ins);
$src = array_merge($src, $array_tail);
return($src);
}
如果你想保留初始数组的键,并添加一个有键的数组,那么使用下面的函数:
function insertArrayAtPosition( $array, $insert, $position ) {
/*
$array : The initial array i want to modify
$insert : the new array i want to add, eg array('key' => 'value') or array('value')
$position : the position where the new array will be inserted into. Please mind that arrays start at 0
*/
return array_slice($array, 0, $position, TRUE) + $insert + array_slice($array, $position, NULL, TRUE);
}
电话的例子:
$array = insertArrayAtPosition($array, array('key' => 'Value'), 3);
$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)
如果你有正则数组,没有什么特别的,这就可以了。记住,使用array_splice()插入元素实际上意味着在开始索引之前插入。移动元素时要小心,因为向上移动意味着$targetIndex -1,向下移动意味着$targetIndex + 1。
class someArrayClass
{
private const KEEP_EXISTING_ELEMENTS = 0;
public function insertAfter(array $array, int $startIndex, $newElements)
{
return $this->insertBefore($array, $startIndex + 1, $newElements);
}
public function insertBefore(array $array, int $startIndex, $newElements)
{
return array_splice($array, $startIndex, self::KEEP_EXISTING_ELEMENTS, $newElements);
}
}
可以在整数和字符串位置进行插入的函数:
/**
* @param array $array
* @param int|string $position
* @param mixed $insert
*/
function array_insert(&$array, $position, $insert)
{
if (is_int($position)) {
array_splice($array, $position, 0, $insert);
} else {
$pos = array_search($position, array_keys($array));
$array = array_merge(
array_slice($array, 0, $pos),
$insert,
array_slice($array, $pos)
);
}
}
整数的用法:
$arr = ["one", "two", "three"];
array_insert(
$arr,
1,
"one-half"
);
// ->
array (
0 => 'one',
1 => 'one-half',
2 => 'two',
3 => 'three',
)
字符串的用法:
$arr = [
"name" => [
"type" => "string",
"maxlength" => "30",
],
"email" => [
"type" => "email",
"maxlength" => "150",
],
];
array_insert(
$arr,
"email",
[
"phone" => [
"type" => "string",
"format" => "phone",
],
]
);
// ->
array (
'name' =>
array (
'type' => 'string',
'maxlength' => '30',
),
'phone' =>
array (
'type' => 'string',
'format' => 'phone',
),
'email' =>
array (
'type' => 'email',
'maxlength' => '150',
),
)