Tamam ben şöyle bir dizi birleştirir ki (I question bu cevap olarak var) bu işlevi vardır:
Functions
function readArray( $arr, $k, $default = 0 ) {
return isset( $arr[$k] ) ? $arr[$k] : $default ;
}
function merge( $arr1, $arr2 ) {
$result = array() ;
foreach( $arr1 as $k => $v ) {
if( is_numeric( $v ) ) {
$result[$k] = (int)$v + (int) readArray( $arr2, $k ) ;
} else {
$result[$k] = merge( $v, readArray($arr2, $k, array()) ) ;
}
}
return $result ;
}
Usage
$basketA = array( "fruit" => array(), "drink" => array() ) ;
$basketA['fruit']['apple'] = 1;
$basketA['fruit']['orange'] = 2;
$basketA['fruit']['banana'] = 3;
$basketA['drink']['soda'] = 4;
$basketA['drink']['milk'] = 5;
$basketB = array( "fruit" => array(), "drink" => array() ) ;
$basketB['fruit']['apple'] = 2;
$basketB['fruit']['orange'] = 2;
$basketB['fruit']['banana'] = 2;
$basketB['drink']['soda'] = 2;
$basketB['drink']['milk'] = 2;
$basketC = merge( $basketA, $basketB ) ;
print_r( $basketC ) ;
Output
Array
(
[fruit] => Array
(
[apple] => 3
[orange] => 4
[banana] => 5
)
[drink] => Array
(
[soda] => 6
[milk] => 7
)
)
OK this works with 1 flaw I cannot figure out how to fix: if $arr1 is missing something that $arr2 has, it should just use the value from $arr2 but instead omits it all together:
Example
$basketA = array( "fruit" => array(), "drink" => array() ) ;
$basketA['fruit']['apple'] = 1;
$basketA['fruit']['orange'] = 2;
$basketA['fruit']['banana'] = 3;
$basketA['drink']['milk'] = 5;
$basketB = array( "fruit" => array(), "drink" => array() ) ;
$basketB['fruit']['apple'] = 2;
$basketB['fruit']['orange'] = 2;
$basketB['fruit']['banana'] = 2;
$basketB['drink']['soda'] = 2;
$basketB['drink']['milk'] = 2;
$basketC = merge( $basketA, $basketB ) ;
print_r( $basketC ) ;
Output
Array
(
[fruit] => Array
(
[apple] => 3
[orange] => 4
[banana] => 5
)
[drink] => Array
(
[milk] => 7
)
)
Ilk dizi o yoktu çünkü yeni dizide değil nasıl [soda] dikkat edin.
Bunu nasıl düzeltebilirim??
Teşekkürler!