How to merge two arrays by taking over only values from the second array that has the same keys as the first one?

后端 未结 3 1366
后悔当初
后悔当初 2020-12-17 23:56

I\'d like to merge two arrays with each other:

$filtered = array(1 => \'a\', 3 => \'c\');
$changed = array(2 => \'b*\', 3 => \'c*\');
         


        
3条回答
  •  被撕碎了的回忆
    2020-12-18 00:21

    This should do it, if I'm understanding your logic correctly:

    array_intersect_key($changed, $filtered) + $filtered
    

    Implementation:

    $filtered = array(1 => 'a', 3 => 'c');
    $changed = array(2 => 'b*', 3 => 'c*');
    $expected = array(1 => 'a', 3 => 'c*');    
    $actual = array_key_merge_deceze($filtered, $changed);
    
    var_dump($expected, $actual);
    
    function array_key_merge_deceze($filtered, $changed) {
        $merged = array_intersect_key($changed, $filtered) + $filtered;
        ksort($merged);
        return $merged;
    }
    

    Output:

    Expected:
    array(2) {
      [1]=>
      string(1) "a"
      [3]=>
      string(2) "c*"
    }
    
    Actual:
    array(2) {
      [1]=>
      string(1) "a"
      [3]=>
      string(2) "c*"
    }
    

提交回复
热议问题