php array_merge() 和 array_replace() 的区别

    /**
     * Symfony\Component\HttpFoundation\ParameterBag
     *  add 使用 了 array_replace() 方法
     * Adds parameters.
     */
    public function add(array $parameters = [])
    {
        $this->parameters = array_replace($this->parameters, $parameters);
    }
/**
 *  array_merge() 和 array_replace() 的区别
 */

$old = [
    0 => 'this is old 0',
    2 => 'this is old 2',
    'name' => 'this is old name',
    'age' => 'this is old age'
];

$new = [
    0 => 'this is new 0',
    1 => 'this is new 1',
    'name' => 'this is new name',
    'age' => 'this is new age',
    'sex' => '男'
];


array_merge($old, $new);

/**
 * 输出如下
 * array_merge()
 * 在数字下标情况下,重排数字下标使其变成有序的,相同key的value值也不会替换
 * 在非数字下标情况下,相同key由后者value替换前者value,将后者key不在前者中的key=>value 插入前者之中
 */
[
    0 => 'this is old 0',
    1 => 'this is old 2',
    'name' => 'this is new name',
    'age' => 'this is new age',
    2 => 'this is new 0',
    3 => 'this is new 1',
    'sex' => '男'
];

array_replace($old,$new);
/**
 * 输出如下
 * 只要key重复由后者value替换前者value
 * 添加后者不在前者中存在的数据
 */
[
    0 => 'this is new 0',
    2 => 'this is old 2',
    1 => 'this is new 1',
    'name' => 'this is new name',
    'age' => 'this is new age',
    'sex' => '男'
];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值