note 95496 deleted from function.array-merge-recursive by danbrown

From: Date: Wed, 06 Jan 2010 15:52:18 +0000
Subject: note 95496 deleted from function.array-merge-recursive by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-164689@lists.php.net to get a copy of this message
Note Submitter: contact at balupton dot com ---- 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', ), ) */ ?>

« previous php.notes (#164689) next »