使用键合并两个不同长度的数组,并将0填充为空

时间:2015-06-02 09:51:09

标签: php arrays

我想在PHP中将两个数组与键合并。如果没有为任何数组定义键,则应将该值填充为零。我想要像

这样的解决方案
array_merge_recursive($a1, $a2)

但它不会产生所需的输出。我编码了以下内容。它有效,但我想知道是否有任何其他好的和有效的解决方案,如array_merge_recursive();

function array_combine_zero_fill($a1,$a2){
    $a3=array();
    foreach($a1 as $k=>$v){
        $a3[$k]['doc1']=$v;
        $a3[$k]['doc2']=array_key_exists($k, $a2) ? $a2[$k]:0;
    }
    foreach($a2 as $k=>$v){
        $a3[$k]['doc1']=array_key_exists($k, $a2) ? $a3[$k]['doc1']:0;
        $a3[$k]['doc2']=$v;
    }
    return $a3;
}

数组结构如下

$a1 = array(
    "apple"=>4,
    "banana"=>2,
    "mango"=>10,
    "guava"=>1,
    "cherry"=>3,
    "grapes"=>7
    );
$a2 = array(
    "pista"=>77,
    "cashew"=>65,
    "almond"=>23,
    "guava"=>34,
    "cherry"=>54,
    "grapes"=>48
    );

所需的结果应如下所示

a3 = Array(
    [apple] => Array([doc1] =>  4, [doc2] =>  0),    
    [banana] => Array([doc1] => 2, [doc2] =>  0),
    [mango] => Array([doc1] => 10, [doc2] =>  0),
    [guava] => Array([doc1] =>  1, [doc2] => 34),
    [cherry] => Array([doc1] => 3, [doc2] => 54),
    [grapes] => Array([doc1] => 7, [doc2] => 48),
    [pista] => Array([doc1] =>  0, [doc2] => 77),
    [cashew] => Array([doc1] => 0, [doc2] => 65),
    [almond] => Array([doc1] => 0, [doc2] => 23)
);

3 个答案:

答案 0 :(得分:5)

// Find all unique keys
$keys = array_flip(array_merge(array_keys($a1), array_keys($a2)));

// create new array
foreach($keys as $k=>$v) {
  $result[$k]['doc1'] = isset($a1[$k]) ? $a1[$k] : 0;
  $result[$k]['doc2'] = isset($a2[$k]) ? $a2[$k] : 0;
  }

  var_dump($result);

答案 1 :(得分:3)

您的代码并不完整。试试这个:

function array_combine_zero_fill($a1, $a2) {
    $a3=array();
    foreach($a1 as $k=>$v){
        $a3[$k]['doc1']=$v;
        $a3[$k]['doc2']=array_key_exists($k, $a2) ? $a2[$k]:0;
    }
    foreach($a2 as $k=>$v){
        // Only add to the array if it's not there, otherwise you just overwrite what was added in the first foreach above.
        if ( ! isset($a3[$k])) {
            $a3[$k]['doc1']=0;
            $a3[$k]['doc2']=$v;
        }
    }
    return $a3;
}

答案 2 :(得分:2)

foreach( array_unique( array_keys( array_merge($a1,$a2) ) ) as $k )
{
    $output[$k]= array("doc1" => array_key_exists( $k, $a1 ) ? $a1[$k] : 0, "doc2" => array_key_exists( $k, $a2 ) ? $a2[$k] : 0 );
}

print_r($output);