PHP Deep Extend Array

后端 未结 7 1798
遇见更好的自我
遇见更好的自我 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:09

    You should use: https://github.com/appcia/webwork/blob/master/lib/Appcia/Webwork/Storage/Config.php#L64

    /**
     * Merge two arrays recursive
     *
     * Overwrite values with associative keys
     * Append values with integer keys
     *
     * @param array $arr1 First array
     * @param array $arr2 Second array
     *
     * @return array
     */
    public static function merge(array $arr1, array $arr2)
    {
        if (empty($arr1)) {
            return $arr2;
        } else if (empty($arr2)) {
            return $arr1;
        }
    
        foreach ($arr2 as $key => $value) {
            if (is_int($key)) {
                $arr1[] = $value;
            } elseif (is_array($arr2[$key])) {
                if (!isset($arr1[$key])) {
                    $arr1[$key] = array();
                }
    
                if (is_int($key)) {
                    $arr1[] = static::merge($arr1[$key], $value);
                } else {
                    $arr1[$key] = static::merge($arr1[$key], $value);
                }
            } else {
                $arr1[$key] = $value;
            }
        }
    
        return $arr1;
    }
    

提交回复
热议问题