简体   繁体   中英

PHP update array with values and keys from another array

I have two arrays:

$a = [
    36 => 7,
    38 => 9,
    41 => 12,
    42 => 5
];

$b = [
    38 => 9,
    41 => 9,
    42 => 5
];

Array a has one extra key[36] and array b has a different value for key[41] .

How do i set a key in a to equal 0 if it is not in b and then how do i update a key in a if it has a different value in b and how do i add new keys to a if it is in b and not in a ?

For now i've made this code:

foreach($a as $key => $value){
    if(array_key_exists($key, $b) && $value != $b[$key]){
        $a[$key] = $b[$key];
    } else{
        $a[$key] = 0;
    }
}

if($diff = array_diff_key($b, $a)){
    foreach($diff as $key => $value){
        $a[$key] = $value;
    }
}

ksort($a);
print_r($a);

And it works but i feel like there should be a much easier way :-s

Update a key in a if it has a different value in b and how do i add new keys to a if it is in b and not in a

$a = array_replace($a, $b);

Set a key in a equal to 0 if it is not in b

foreach(array_diff_key($a, $b) as $k=>$v) {
   $a[$k] = 0;
}

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM