Alex Rivera | Logout

PHP Deep Extend Array

Asked 2012-10-04T10:17:48.383
22

How can I do a deep extension of a multi dimensional associative array (for use with decoded JSON objects). I need the php equivalent of jQuery's $.extend(true, array1, array2) with arrays instead of JSON and in PHP.

Here's an example of what I need (array_merge_recursive didn't seem to do the same thing)

$array1 = ('1'=> ('a'=>'array1a', 'b'=>'array1b'));
$array2 = ('1'=> ('a'=>'array2a', 'c'=>'array2b'));

$array3 = array_extend($array1, $array2);

//$array3 = ('1'=> ('a'=>'array2a', 'b'=>'array1b', 'c'=>'array2b'))

Notice how array2 overrides array1 if it has same value (like how extension of classes works)

Edit
Report

1 Answer

0

With a little googling I found this:

/**
 * jquery style extend, merges arrays (without errors if the passed values are not arrays)
 *
 * @return array $extended
 **/
function extend() {
    $args = func_get_args();
    $extended = array();
    if(is_array($args) && count($args)) {
        foreach($args as $array) {
            if(is_array($array)) {
                $extended = array_merge($extended, $array);
            }
        }
    }
    return $extended;
}

extend($defaults, $new_options);
answered 2013-02-06T16:17:33.997

Your Answer