如何将一个新项目插入到数组的任何位置,例如在数组的中间?
当前回答
可以在整数和字符串位置进行插入的函数:
/**
* @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',
),
)
其他回答
你可以试试,用这个方法让它变得简单
/**
* array insert element on position
*
* @link https://vector.cool
*
* @since 1.01.38
*
* @param array $original
* @param mixed $inserted
* @param int $position
* @return array
*/
function array_insert(&$original, $inserted, int $position): array
{
array_splice($original, $position, 0, array($inserted));
return $original;
}
$columns = [
['name' => '預約項目', 'column' => 'item_name'],
['name' => '預約時間', 'column' => 'start_time'],
['name' => '預約姓名', 'column' => 'full_name'],
['name' => '連絡電話', 'column' => 'phone'],
['name' => '建立時間', 'column' => 'create_time']
];
$col = ['name' => '預約帳戶', 'column' => 'user_id'];
$columns = array_insert($columns, $col, 3);
print_r($columns);
打印:
Array
(
[0] => Array
(
[name] => 預約項目
[column] => item_name
)
[1] => Array
(
[name] => 預約時間
[column] => start_time
)
[2] => Array
(
[name] => 預約姓名
[column] => full_name
)
[3] => Array
(
[name] => 報名人數1
[column] => num_of_people
)
[4] => Array
(
[name] => 連絡電話
[column] => phone
)
[5] => Array
(
[name] => 預約帳戶
[column] => user_id
)
[6] => Array
(
[name] => 建立時間
[column] => create_time
)
)
这个由Brad Erickson编写的函数用于关联数组:
/* * Inserts a new key/value after the key in the array. * * @param $key * The key to insert after. * @param $array * An array to insert in to. * @param $new_key * The key to insert. * @param $new_value * An value to insert. * * @return * The new array if the key exists, FALSE otherwise. * * @see array_insert_before() */ function array_insert_after($key, array &$array, $new_key, $new_value) { if (array_key_exists($key, $array)) { $new = array(); foreach ($array as $k => $value) { $new[$k] = $value; if ($k === $key) { $new[$new_key] = $new_value; } } return $new; } return FALSE; }
函数来源-这篇博文。还有一个方便的功能,以插入之前特定的关键。
如何使用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
如果你有正则数组,没有什么特别的,这就可以了。记住,使用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);
}
}
没有本地PHP函数(据我所知)可以完全完成您的请求。
我已经写了2个我认为适合目的的方法:
function insertBefore($input, $index, $element) {
if (!array_key_exists($index, $input)) {
throw new Exception("Index not found");
}
$tmpArray = array();
$originalIndex = 0;
foreach ($input as $key => $value) {
if ($key === $index) {
$tmpArray[] = $element;
break;
}
$tmpArray[$key] = $value;
$originalIndex++;
}
array_splice($input, 0, $originalIndex, $tmpArray);
return $input;
}
function insertAfter($input, $index, $element) {
if (!array_key_exists($index, $input)) {
throw new Exception("Index not found");
}
$tmpArray = array();
$originalIndex = 0;
foreach ($input as $key => $value) {
$tmpArray[$key] = $value;
$originalIndex++;
if ($key === $index) {
$tmpArray[] = $element;
break;
}
}
array_splice($input, 0, $originalIndex, $tmpArray);
return $input;
}
虽然速度更快,而且可能更节省内存,但这只适用于不需要维护数组键的地方。
如果你确实需要维护密钥,下面的方法会更合适;
function insertBefore($input, $index, $newKey, $element) {
if (!array_key_exists($index, $input)) {
throw new Exception("Index not found");
}
$tmpArray = array();
foreach ($input as $key => $value) {
if ($key === $index) {
$tmpArray[$newKey] = $element;
}
$tmpArray[$key] = $value;
}
return $input;
}
function insertAfter($input, $index, $newKey, $element) {
if (!array_key_exists($index, $input)) {
throw new Exception("Index not found");
}
$tmpArray = array();
foreach ($input as $key => $value) {
$tmpArray[$key] = $value;
if ($key === $index) {
$tmpArray[$newKey] = $element;
}
}
return $tmpArray;
}