当前位置:网站首页>PHP中array_merge的坑
PHP中array_merge的坑
2022-07-24 15:41:00 【aben_sky】
PHP官方文档对array_merge的定义
array_merge( array $array1[, array $...] ) : array
array_merge() 将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。
如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。
如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。
对坑的说明
看上面的文档的粗体字部分, 如果你信了, 并且只是相信文档说的这一种情况, 那你就错了.
看文档给的例子:
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
var_dump($result);
结果是:
Array
(
[0] => data
)
嗯, 对, 文档给的这个例子没有问题, 确实没有任何问题.
但是, 如果两个数组都不为空, 且有数字下标, 它一样会将数字下标重新索引
$arr = [
11 => 'a',
12 => 'b'
];
$arr2 = [
'a' => 'a1',
14 => 'b1'
];
var_dump(array_merge($arr, $arr2));
结果是:
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
["a"]=>
string(2) "a1"
[2]=>
string(2) "b1"
}
数字下标都被重置了!
so, 这种情况下只能使用 + 来处理:
$result = $arr + $arr2;
边栏推荐
- Application modification log path log4j.properties
- 从哪些维度评判代码质量的好坏?如何具备写出高质量代码的能力?
- 请问好的券商的排名?网上开户安全吗
- Join parameter processing and @param
- 2022/7/18 CF training
- ReentrantLock 可重入锁
- Windows10安装免安装版redis
- Kubectl_好用的命令行工具:oh-my-zsh_技巧和窍门
- [tf.keras]: a problem encountered in upgrading the version from 1.x to 2.x: invalidargumenterror: cannot assign a device for operation embedding_
- [shaders realize pixelate mosaic effect _shader effect Chapter 7]
猜你喜欢

Which is a good noise reduction Bluetooth headset? Ranking of the most cost-effective noise reduction Bluetooth headsets

2022 robocom world robot developer competition - undergraduate group (provincial competition) -- fifth question tree and bipartite diagram (completed)

微调LayoutLM v3进行票据数据的处理和内容识别

MySQL之知识点(十二)

【量化测试】

Istio1.12:安装和快速入门

接参处理和@Param

Dynamics 365: explain virtual entity from 0 to 1

Using JS to implement click events

Yolo5face: why reinvent the face detector
随机推荐
2022 robocom world robot developer competition - undergraduate group (provincial competition) CAIP full version solution
Experience summary of slow SQL problems
Scala functions and their higher-order applications
torch_ How to use scatter. Scatter() in detail
Error 1053: the service did not respond to the start or control request in a timely fashion
遭受DDoS时,高防IP和高防CDN的选择
Force button 31. Next arrangement -- double finger needling
Class assignment (6) - 575. Word division (word)
Personal practical experience: Data Modeling "whether account data belongs to dimension or account domain"
R语言ggplot2可视化:ggplot2可视化基本散点图(scatter plot)、通过在theme_bw中指定参数base_size来改变轴标签的大小、并控制网格线和轴标签的大小
Varnish4.0 cache agent configuration
接参处理和@Param
MySQL source code analysis -- data structure of index
Memorythrashing: Tiktok live broadcast to solve memory dithering practice
Azure key vault (1) Introduction
Lsyncd real time synchronization
Windows10安装免安装版redis
SQL row to column, column to row
Read the paper with me - multi model text recognition network
Kubernetes version docking object storage