note 95496 added to function.array-merge-recursive
| From: | contact at balupton dot com | Date: | Wed, 06 Jan 2010 14:23:14 +0000 |
| Subject: | note 95496 added to function.array-merge-recursive | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-164679@lists.php.net to get a copy of this message | ||
I've done some work below, so that it will only merge arrays that have keys, for normal arrays
it will replace. I've also removed references as php magically references until a change is
made, we don't make any changes to references (only merge) so it is quicker without
referencing.
<?php
/**
* Will merge the keys of arrays together. For a normal array we replace.
* @version 1, January 06, 2010
* @param array ...
* @return array
* @author Benjamin "balupton" Lupton <contact@balupton.com> {@link http://www.balupton.com/}
* @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
* @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
*/
function array_merge_recursive_keys ( ) {
# Prepare
$args = func_get_args();
$merged = array_shift($args);
# Handle
foreach ( $args as $array ) {
# Prepare
if ( !is_array($array) ) $array = array($array);
# Check if we have keys
if ( is_numeric(implode('',array_keys($array))) ) {
# We don't
$merged = $array;
}
else {
# We do, cycle through keys
foreach ( $array as $key => $value ) {
# Merge
if ( is_array($value) && array_key_exists($key, $merged) &&
is_array($merged[$key]) ) {
# Array is keyed array
$merged[$key] = array_merge_recursive_keys($merged[$key], $value);
}
else {
# Normal
$merged[$key] = $value;
}
}
}
}
# Done
return $merged;
}
/*
$a = array(
'register' => array(
'user' => array(
'id' => 1,
'title' => 'hello'
)
),
'field' => array(
'one','two','three'
)
);
$b = array(
'register' => array(
'user' => array(
'id' => 1,
'avatar' => 'file'
)
),
'field' => array(
'four','five'
)
);
$c = array_merge_recursive_keys($a, $b);
$c = array (
'register' => array (
'user' => array (
'id' => 1,
'title' => 'hello',
'avatar' => 'file',
),
),
'field' => array (
0 => 'four',
1 => 'five',
),
)
*/
?>
----
Server IP: 69.147.83.197
Probable Submitter: 124.169.148.238
----
Manual Page -- http://www.php.net/manual/en/function.array-merge-recursive.php
Edit -- https://master.php.net/note/edit/95496
Del: integrated -- https://master.php.net/note/delete/95496/integrated
Del: useless -- https://master.php.net/note/delete/95496/useless
Del: bad code -- https://master.php.net/note/delete/95496/bad+code
Del: spam -- https://master.php.net/note/delete/95496/spam
Del: non-english -- https://master.php.net/note/delete/95496/non-english
Del: in docs -- https://master.php.net/note/delete/95496/in+docs
Del: other reasons-- https://master.php.net/note/delete/95496
Reject -- https://master.php.net/note/reject/95496
Search -- https://master.php.net/manage/user-notes.php