PHP Deep Extend Array

后端 未结 7 1414
遇见更好的自我
遇见更好的自我 2020-12-31 01:53

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, arr

7条回答
  •  醉梦人生
    2020-12-31 02:02

    I guess here is the correct answer, because:

    • your answer have a bug with warning:

      Warning: Cannot use a scalar value as an array in...

    Because $a is not always an array and you use $a[$k].

    • array_merge_recursive does indeed merge arrays, but it converts values with duplicate keys to arrays rather than overwriting the value in the first array with the duplicate value in the second array, as array_merge does.

    • other aswers are not recursives or not simple.

    So, here is my answer: your answer without bugs:

    function array_extend(array $a, array $b) {
        foreach($b as $k=>$v) {
            if( is_array($v) ) {
                if( !isset($a[$k]) ) {
                    $a[$k] = $v;
                } else {
                    if( !is_array($a[$k]){
                        $a[$k]=array();
                    }
                    $a[$k] = array_extend($a[$k], $v);
                }
            } else {
                $a[$k] = $v;
            }
        }
        return $a;
    }
    

    And my answer with ternary operator:

    function array_extend(array $a, array $b){
        foreach($b as $k=>$v)
                $a[$k] = is_array($v)&&isset($a[$k])?
                    array_extend(is_array($a[$k])?
                            $a[$k]:array(),$v):
                    $v;
        return $a;
    }
    

    Edit: And a bonus one with as many arrays you want:

    function array_extend(){
        $args = func_get_args();
        while($extended = array_shift($args))
                if(is_array($extended))
                        break;
        if(!is_array($extended))
                return FALSE;
        while($array = array_shift($args)){
            if(is_array($array))
                    foreach($array as $k=>$v)
                            $extended[$k] = is_array($v)&&isset($extended[$k])?
                                array_extend(is_array($extended[$k])?
                                        $extended[$k]:array(),$v):
                                $v;
        }
        return $extended;
    }
    

提交回复
热议问题