note 16705 deleted from function.array-merge-recursive by sniper
| From: | sniper@php.net | Date: | Mon, 06 Oct 2003 22:59:19 +0000 |
| Subject: | note 16705 deleted from function.array-merge-recursive by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-57939@lists.php.net to get a copy of this message | ||
Note Submitter: dev-null@christophe.vg
----
Another annoying behaviour is the fact that two scalars are merged together into an array, thus
changing the type of a given item.
To have a more "logical" merge of two array "trees", I wrote this solution ...
<?
$ar1 = array( 'a1' => 1,
'a2' => array( 1, 2, 3 ),
'a3' => array( 'a' => array( 10, 20, 30 ), 'b' =>
'b' ) );
$ar2 = array( 'a1' => 2,
'a2' => array( 3, 4, 5 ),
'a3' => array( 'c' => 'cc', 'a' => array(
10, 40 ) ) );
function is_hash( $var ) {
if( is_array( $var ) ) {
$keys = array_keys( $var );
$all_num = true;
for( $i=0; $i<count($keys); $i++ )
if( is_string($keys[$i] ) ) return true;
}
return false;
}
function array_join_merge( $arr1, $arr2 ) {
if( is_array( $arr1 ) and is_array( $arr2 ) ) {
// the same -> merge
$new_array = array();
if( is_hash( $arr1 ) and is_hash( $arr2 ) ) {
// hashes -> merge based on keys
$keys = array_merge( array_keys( $arr1 ), array_keys( $arr2 ) );
foreach( $keys as $key ) {
$new_array[$key] = array_join_merge( $arr1[$key], $arr2[$key] );
}
} else {
// two real arrays -> merge
$new_array =
array_reverse(array_unique(array_reverse(array_merge($arr1,$arr2))));
}
return $new_array;
} else {
// not the same ... take new one if defined, else the old one stays
return $arr2 ? $arr2 : $arr1;
}
}
$result = array_join_merge( $ar1, $ar2 );
print_r( $result );
// to illustrate the problem ...
$result = array_merge_recursive( $ar1, $ar2 );
print_r( $result );
?>