La funzione è presa dai commenti di array_merge_recursive
Codice PHP:
<?php
$prodotti1 = array(3=>2,5=>1,7=>3,1=>2);
$prodotti2 = array(9=>3,5=>2);
echo '<pre>';
print_r($prodotti1);
print_r($prodotti2);
function array_merge_recursive_keep_keys( $arrElement1 , $arrElement2 , $intCount = 0 ) {
$arrNew = array();
$arrElement1Keys = array_keys( $arrElement1 );
$arrElement2Keys = array_keys( $arrElement2 );
$arrDifKeys1 = array_diff( $arrElement1Keys, $arrElement2Keys );
$arrDifKeys2 = array_diff( $arrElement2Keys, $arrElement1Keys );
$arrInter = array_intersect( $arrElement1Keys , $arrElement2Keys );
foreach( $arrDifKeys1 as $strKey1)
{
$arrNew[ $strKey1 ] = $arrElement1[ $strKey1 ];
}
foreach( $arrDifKeys2 as $strKey2)
{
$arrNew[ $strKey2 ] = $arrElement2[ $strKey2 ];
}
foreach( $arrInter as $strInterKey )
{
if( is_array( $arrElement1[ $strInterKey ] ) && is_array( $arrElement2[ $strInterKey ] ) )
{
$intCount++;
$arrNew[ $strInterKey ] = array_merge_recursive_keep_keys( $arrElement1[ $strInterKey ] , $arrElement2[ $strInterKey ] , $intCount );
}
elseif( is_array( $arrElement1[ $strInterKey ] ) || is_array( $arrElement2[ $strInterKey ] ) )
{
$arrNew[ $strInterKey ][] = $arrElement1[ $strInterKey ];
$arrNew[ $strInterKey ][] = $arrElement2[ $strInterKey ];
}
else
{
$arrNew[ $strInterKey ] = array();
$arrNew[ $strInterKey ][] = $arrElement1[ $strInterKey ];
$arrNew[ $strInterKey ][] = $arrElement2[ $strInterKey ];
}
}
return $arrNew;
}
$unisci = array_merge_recursive_keep_keys($prodotti1,$prodotti2);
print_r($unisci);
foreach($unisci as $k => $v) {
if (!is_array($v) )
$finale[$k] = $v;
else {
$tot = 0;
foreach($v as $value)
$tot+=$value;
$finale[$k] = $tot;
}
}
ksort($finale);
reset($finale);
print_r($finale);
?>