Insert new item in array on any position in PHP
我如何在任何位置插入一个新项目到数组中,例如在数组中间?
You may find this a little more intuitive. It only requires one function call to array_splice
:
$original = array( 'a', 'b', 'c', 'd', 'e' );
$inserted = array( 'x' ); // Not necessarily an array
array_splice( $original, 3, 0, $inserted ); // splice in at position 3
// $original is now a b c x d e
A function that can insert at both integer and string positions:
/**
* @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)
);
}
}
Integer usage:
$arr = ["one", "two", "three"];
array_insert(
$arr,
1,
"one-half"
);
// ->
array (
0 => 'one',
1 => 'one-half',
2 => 'two',
3 => 'three',
)
String Usage:
$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',
),
)
$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)
链接地址: http://www.djcxy.com/p/58938.html
上一篇: 如何将元素添加到PHP中的空数组?
下一篇: 在PHP中的任何位置插入数组中的新项目