PHP array_merge 不工作

PHP array_merge not working

与 PHP 一起工作。 我有带有此键和值的数组 1:

$array_1 = array(
(more values)
'propub_cost_max' => 5,
'propub_cost_min' => 0.5,
'average_calc_last' => '-1 Months',
'propub_qtd_first_offer' => 4
);

和数组 2:

$array_2 = array(
'propub_cost_max' => 20,
'propub_cost_min' => (no value),
'average_calc_last' => (no value),
'propub_qtd_first_offer' => (no value)
);

我想将数组 2 与数组 1 合并,所以我这样做了:

$result = array_merge($array_2, $array_1);

但结果是:

$result = array(
(more values)
'propub_cost_max' => 5,
'propub_cost_min' => 0.5,
'average_calc_last' => '-1 Months',
'propub_qtd_first_offer' => 4
);

propub_cost_max 键的值应该是 20,对吗?

思路就是保留一些值,当然有值的时候就替换值不同的地方。 我认为 array_merge 应该可以,但是...

谢谢大家

"If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.". in your case array_1 is the latter.

nogad

(link 到 array_merge

还有

You have a } instead of a parenthesis.

正如所说 TheValyreanGroup.

这两个都是完全正确的。所以

$result = array_merge($array_1, $array_2); 

将解决您的问题。交换值,以便 $array_2 现在将覆盖 $array_1.

中的值

为了解决您想要更新 一些 值的整体问题,而不知道您想要保留哪些值和哪些条件,我们简化为不使用空值覆盖值一个,所以 :

$array_2 = array_filter($array_2); //clears empty values
$result = array_merge($array_1, $array_2); // as before. updates non-empty new values.

这将解决您的问题

array_merge_recursive($array_1, $array_2);