php array_merge without erasing values?

前端 未结 6 1058
南旧
南旧 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:41

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

     '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:

     '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,

    $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));
    ?>
    

提交回复
热议问题