php array_merge without erasing values?

前端 未结 6 1042
南旧
南旧 2020-12-16 15:23

Background: Trevor is working with a PHP implementation of a standard algorithm: take a main set of default name-value pairs, and update those name-value pa

相关标签:
6条回答
  • 2020-12-16 15:33
    array_replace_recursive($array, $array2);
    

    This is the solution.

    0 讨论(0)
  • 2020-12-16 15:40

    Well, if you want a "clever" way to do it, here it is, but it may not be as readable as simply doing a loop.

    $merged = array_merge(array_filter($foo, 'strval'), array_filter($bar, 'strval'));
    

    edit: or using +...

    0 讨论(0)
  • 2020-12-16 15:40

    Try this:

    $merged = array_map(
        create_function('$foo,$bar','return ($bar?$bar:$foo);'),
        $foobar,$feebar
    );
    

    Not the most readable solution, but it should replace only non-empty values, regardless of which order the arrays are passed..

    0 讨论(0)
  • 2020-12-16 15:41

    This will put duplicates into a new array, I don't know if this is what you want though.

    <?php
      $foobar =   Array('firstname' => 'peter','age' => '33',);
      $feebar =   Array('firstname' => '','lastname' => 'griffin',);
      $merged=$foobar;
      foreach($feebar as $k=>$v){
        if(isset($foobar[$k]))$merged[$k]=array($v,$foobar[$k]);
        else $merged[$k]=$v;
      }
      print_r($merged);
    ?>
    

    This will simply assure that feebar will never blank out a value in foobar:

    <?php
      $foobar =   Array('firstname' => 'peter','age' => '33',);
      $feebar =   Array('firstname' => '','lastname' => 'griffin',);
      $merged=$foobar;
      foreach($feebar as $k=>$v) if($v)$merged[$k]=$v;
      print_r($merged);
    ?>
    

    or ofcourse,

    <?
      function cool_merge($array1,$array2){
        $result=$array1;
        foreach($array2 as $k=>$v) if($v)$result[$k]=$v;
        return $result;
      }
    
      $foobar =   Array('firstname' => 'peter','age' => '33',);
      $feebar =   Array('firstname' => '','lastname' => 'griffin',);
      print_r(cool_merge($foobar,$feebar));
    ?>
    
    0 讨论(0)
  • 2020-12-16 15:53

    If you also want to keep the values that are blank in both arrays:

    array_filter($foo) + array_filter($bar) + $foo + $bar
    
    0 讨论(0)
  • 2020-12-16 15:56

    Adjust to your needs:

    # Replace keys in $foo
    foreach ($foo as $key => $value) {
        if ($value != '' || !isset($bar[$key])) continue;
        $foo[$key] = $bar[$key];
    }
    
    # Add other keys in $bar
    # Will not overwrite existing keys in $foo
    $foo += $bar;
    
    0 讨论(0)
提交回复
热议问题