Home >Backend Development >PHP Tutorial >求一个高效简单的多维数组字符编码转换函数

求一个高效简单的多维数组字符编码转换函数

WBOY
WBOYOriginal
2016-06-06 20:51:071109browse

function arrayCv($data) {
		if (is_array($data)) {
			
			foreach ($data as $key => $val) {
				if (!is_array($val)) {
					$arr[$key] = iconv('UTF-8', 'GBK',  $val);
				} else {

					$arr[$key] = arrayCv($val);
				}
			}
		} else {
			return iconv('UTF-8', 'GBK',  $data);
		}
		return $arr;

	}

现在是这个样的感觉不优雅,有用array_map, array_walk来实现的吗

回复内容:

function arrayCv($data) {
		if (is_array($data)) {
			
			foreach ($data as $key => $val) {
				if (!is_array($val)) {
					$arr[$key] = iconv('UTF-8', 'GBK',  $val);
				} else {

					$arr[$key] = arrayCv($val);
				}
			}
		} else {
			return iconv('UTF-8', 'GBK',  $data);
		}
		return $arr;

	}

现在是这个样的感觉不优雅,有用array_map, array_walk来实现的吗

试试 array_walk_recursive 。

function arrayCv($data) {
      if (is_array($data)) {
            foreach ($data as $key => $val) {
                 $arr[$key]=arrayCv($val);
           }
      } else {
             return iconv('UTF-8', 'GBK',  $data);
      }
}

==================================================

function myConv(&$value,$key) 
{
    $value=iconv('UTF-8', 'GBK',$value);
}
function arrayCv($data) {
    array_walk($data,"myConv");
}

function ac($input = array()){
    return json_decode(iconv('UTF-8', 'GBK//IGNORE',  json_encode($input,JSON_UNESCAPED_UNICODE)),true);
}

不知道这个行不行。有人用php5.4么。测测。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn