Home > Backend Development > PHP Tutorial > 怎么给数组转换编码

怎么给数组转换编码

WBOY
Release: 2016-06-13 12:11:42
Original
893 people have browsed it

如何给数组转换编码
做了一个要变成的Json的二维数组,请问用什么方法能把这个二维数组转换编码?原来是gb2312的
用mb_convert_encoding()只能转换字符串的吧?
------解决思路----------------------

function gbk2utf8(&$array){<br />	static $i = 0;<br />	if (++$i > 1000) {<br />		die('possible deep recursion attack');<br />	}<br />	foreach ($array as $key => $value) {<br />		if (is_array($value)) {<br />			gbk2utf8($array[$key]);<br />		} else {<br />			$array[$key] = iconv('GB2312','UTF-8',$value);<br />		}<br />	}<br />	$i--;<br />}
Copy after login

------解决思路----------------------
如果键不是中文的
array_walk_recursive($ar, function(&$v) {<br />  $v = iconv('gbk', 'utf-8', $v);<br />});<br />
Copy after login


如果键有中文的,可以这样
parse_str(iconv('gbk', 'utf-8', urldecode(http_build_query($ar))), $ar);<br />
Copy after login
未经严密测试,不保证正确
------解决思路----------------------
 function turn_ro($arr){
$new_arr = array();
foreach($arr as $key=>$value){

$key1 = iconv('gb2312','utf-8',$key);
$value1 = iconv('gb2312','utf-8',$value);
$new_arr[$key1] = $value1;
}
return $new_arr;
}


$arr1 = Array (
Array ( 
'测试键-' => '测试纸1',
'测试键2' => '测试之二',
'brand_name' => 'TCI',
'pro_info' => '耗材',
'parent_categ_code' => 'S',
'child_categ_code' => 'S',

'create_time' => '1415774748' ),
Array (
'测试键-' => '测试纸1',
'测试键2' => '测试之二',
'brand_name' => 'TCI',
'sup_name' => '百灵威',
'cn_name' => 'EthylAcetate',
'en_name' => '乙酸乙酯1',
'pinyin' => 'yisuanyizhi',
'pro_info' => '文具',
'parent_categ_code' => 'S',
'child_categ_code' => 'S',

'create_time' => '1415774748' ),


);

$new_arr = array_map('turn_ro',$arr1);

print_r($new_arr);
针对二维数组的,多维不能用此方法

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template