Encode a multidimensional array
This is how you can encode the values of an multidimensional array using two functions. You could of course optimize it to one, by moving the mb_convert_encoding-function into the first condition of the convert2encodingRecursive-function. But in my case I needed the string converter as well.
<?php
    /**
     * Convert a string to encoding, default UTF-8
     * 
     * @param type $string
     * @return type
     */
    public function convert2encoding($string, $encoding = "UTF-8") {
        return mb_convert_encoding($string, $encoding, mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
    }
    
    /**
     * Recursive encoding of multidimensional arrays
     * @param type $array
     * @param type $encoding
     */
    public function convert2encodingRecursive($array, $encoding = "UTF-8") {
        if(is_array($array)){
            $out = array();
            foreach ($array as $key => $value) {
                if(is_string($value)){
                    $out[$key] = $this->convert2encoding($value, $encoding);
                }else{
                    $out[$key] = $this->convert2encodingRecursive($value, $encoding);
                }
                
            }
            return $out;
        }
    }
?>This is how you can optimize the above
<?php
replace
 $out[$key] = $this->convert2encoding($value, $encoding);
with
 $out[$key] = mb_convert_encoding($string, $encoding, mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
into one function:
    public function convert2encodingRecursive($array, $encoding = "UTF-8") {
        if(is_array($array)){
            $out = array();
            foreach ($array as $key => $value) {
                if(is_string($value)){
                    $out[$key] = mb_convert_encoding($string, $encoding, mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
                }else{
                    $out[$key] = $this->convert2encodingRecursive($value, $encoding);
                }
                
            }
            return $out;
        }
    }
?>Knowledge keywords: 
