array_merge in PHP 未覆盖值

array_merge in PHP not overriding values

我在使用 array_merge 时遇到了一些奇怪的问题。

我的2个数组如下;

$original = array(
    'details' => array('error' => 0)
    'maxWidth' => 700,
    'maxHeight' => 700,
    'size' => 'original'
);

$defaults = array(
    'details' => array(),
    'maxWidth' => 1024,
    'maxHeight' => 1024,
    'size' => 'original'
);

但是当我这样做的时候

$merge = array_merge($defaults, $original);

它不会用更新后的值 1024 替换 maxWidth 和 maxHeight,而是将它们保持在 700

知道我该如何解决这个问题吗?

来自the documentation(我强调):

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.

所以目前您从 $defaults 的值开始,然后用 $original 覆盖。只需切换阵列:

$merge = array_merge($original, $defaults);