如何将一个新项目插入到数组的任何位置,例如在数组的中间?
当前回答
基于@Halil的伟大回答,这里是一个简单的函数如何在特定的键后插入新元素, 同时保留整型键:
private function arrayInsertAfterKey($array, $afterKey, $key, $value){
$pos = array_search($afterKey, array_keys($array));
return array_merge(
array_slice($array, 0, $pos, $preserve_keys = true),
array($key=>$value),
array_slice($array, $pos, $preserve_keys = true)
);
}
其他回答
可以在整数和字符串位置进行插入的函数:
/**
* @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
)
)
这可以通过array_splice完成,但是,当插入数组或使用字符串键时,array_splice会失败。我写了一个函数来处理所有情况:
function array_insert(&$arr, $index, $val)
{
if (is_string($index))
$index = array_search($index, array_keys($arr));
if (is_array($val))
array_splice($arr, $index, 0, [$index => $val]);
else
array_splice($arr, $index, 0, $val);
}
你可能会觉得这更直观一些。它只需要调用array_splice一个函数:
$original = array( 'a', 'b', 'c', 'd', 'e' );
$inserted = array( 'x' ); // not necessarily an array, see manual quote
array_splice( $original, 3, 0, $inserted ); // splice in at position 3
// $original is now a b c x d e
如果replacement只是一个元素,则没有必要在它周围加上array(),除非该元素本身是数组、对象或NULL。
RETURN VALUE:需要注意的是,函数不返回所需的替换。$original通过引用传递,并在适当的位置进行编辑。请参阅参数列表中带有&的表达式array &$array。
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;
}
推荐文章
- 用“+”(数组联合运算符)合并两个数组如何工作?
- Laravel PHP命令未找到
- 如何修复从源代码安装PHP时未发现xml2-config的错误?
- 在PHP中对动态变量名使用大括号
- 使arrayList.toArray()返回更具体的类型
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?
- PHP字符串中的花括号
- PHP -如何最好地确定当前调用是否来自CLI或web服务器?
- 无法打开流:没有这样的文件或目录
- 在php中生成一个随机密码
- 如何通过PHP检查URL是否存在?
- .Net数据结构:ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary—速度,内存,以及何时使用每个?
- 如何防止页面刷新时重新提交表单(F5 / CTRL+R)
- 如何为已安装的Ubuntu LAMP堆栈启用cURL ?