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)
);
// 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);
Your code isn't quite complete. Try this:
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;
}
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);