php使用相同的键更新数组的值

时间:2015-07-02 08:59:22

标签: php

如何使用新值更新相同的数组键

Array ( [key1] => 3 [key2] => 2 [key3] => 1  [key4] => 2) 

Array ( [key3] => 6 ) 

预期答案:

Array ( [key1] => 3 [key2] => 2 [key3] => 6  [key4] => 2)

2 个答案:

答案 0 :(得分:0)

试试这个,

$first_array = array('key1' => 3,'key2' => 2,'key3' => 1,'key4' => 2);
$second_array = array('key3' => 6);
foreach ($first_array as $key => $value) {
    if(isset($second_array[$key])) {
        $first_array[$key] = $second_array[$key];
    }
}
var_dump($first_array);

答案 1 :(得分:0)

试试这个..

<?php
$A = array('key1' => 3, 'key2' => 2, 'key3' => 1, 'key4' => 2);
 $B = array('key3' => 6);

 $result=array_merge($A, $B);

print_r($result);
?>

结果:Array ( [key1] => 3 [key2] => 2 [key3] => 6 [key4] => 2 )

价:https://eval.in/391016