前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >PHP合并数组的几种方法比较

PHP合并数组的几种方法比较

原创
作者头像
俗可耐
修改2018-07-27 14:25:06
7K0
修改2018-07-27 14:25:06
举报
文章被收录于专栏:俗人笔记俗人笔记

概述

php合并数组一般有三个方法

  1. 使用array_merge函数
  2. 使用array_merge_recursive函数
  3. 使用操作符+

对比差异

array_merge+的比较

  1. 对于字符串索引,array_merge以后面的数组为准,覆盖前面数组相应的值;+操作以前面的数组为准
  2. 对于数字索引,array_merge会同时保留所有数组的对应的值,并且把索引从0重排;+操作处理数字索引的策略和处理字符串索引一致:以前面的数组为准,且保留原索引

array_mergearray_merge_recursive的比较

  1. 对于相同的字符串索引,array_merge_recursive会把所有的值合并成一个数组,而array_merge会以后面的数组为准
  2. 对于数字索引,两者都会保留全部的值,并把索引从0重排

注意

  • array_merge只传入一个数组参数时,会把参数中的数组索引从0重排
  • array_merge_recursive对于相同的字符串索引,如果值仍是数组,则会对数组再次合并当做此索引的值

代码示例

代码语言:txt
复制
$arr1 = [
    2 => 'super',
    1 => 'star',
    'hello' => 'my world',
    'arr' => [
        3 => 'ha',
        2 => 'ya',
        'hello' => 'wa',
    ]
];
$arr2 = [
    1 => 'lets',
    2 => 'laugh',
    'hello' => 'your world',
    'arr' => [
        'yes no'
    ]
];

print_r(array_merge($arr1, $arr2));

print_r($arr1 + $arr2);

print_r(array_merge_recursive($arr1, $arr2));

以上代码输出为:

代码语言:txt
复制
Array
(
    [0] => super
    [1] => star
    [hello] => your world
    [arr] => Array
        (
            [0] => yes no
        )

    [2] => lets
    [3] => laugh
)
Array
(
    [2] => super
    [1] => star
    [hello] => my world
    [arr] => Array
        (
            [3] => ha
            [2] => ya
            [hello] => wa
        )

)
Array
(
    [0] => super
    [1] => star
    [hello] => Array
        (
            [0] => my world
            [1] => your world
        )

    [arr] => Array
        (
            [3] => ha
            [2] => ya
            [hello] => wa
            [3] => yes no
        )

    [2] => lets
    [3] => laugh
)

Bug

在7.0.20版本中,array_merge_recursive合并相同字符串索引的数组时,合并结果中会有相同的数字索引。

代码语言:txt
复制
$arr1 = [
    'arr' => [
        3 => 'hello',
        2 => 'world',
    ]
];
$arr2 = [
    'arr' => [
        'yes',
        'no'
    ]
];

$result = array_merge_recursive($arr1, $arr2);

print_r($result);

以上代码会输出:

代码语言:txt
复制
Array
(
    [arr] => Array
        (
            [3] => hello
            [2] => world
            [2] => yes
            [3] => no
        )

)

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概述
  • 对比差异
    • array_merge与+的比较
      • array_merge与array_merge_recursive的比较
      • 注意
        • 代码示例
        • Bug
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档