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

I want to merge two arrays with keys in PHP. If no key defined for any array it should fill the value by zero. I wanted solution like

array_merge_recursive($a1, $a2)

But it does not produce the required output. I have coded following. It works but I want to know if there are any other good and efficient solution like 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;
}

The array structure is like following

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

The required result should look like this

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)
);
查看全部
drbii0359
drbii0359
2015/06/02 09:51
  • php
  • arrays
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

3个回复