标签:call compare 解决 name style mat encode tmp lse
php场景中,需要将数组转为json字符串,就需要用到php自带的json_encode函数;
但是当数组中含有中文字符串时,转出来的结果却是以下结果:
1 <?php 2 3 $tmpArr = array( 4 ‘name‘ => ‘长裤‘, 5 ‘color‘ => ‘blue‘, 6 ‘size‘ => ‘XL‘, 7 ‘title‘ => ‘中年男装 长裤‘ 8 ); 9 10 $tmpJson = json_encode($tmpArr); 11 12 echo $tmpJson;
输出:{"name":"\u957f\u88e4","color":"blue","size":"XL","title":"\u4e2d\u5e74\u7537\u88c5 \u957f\u88e4"}
需要中文不被转换,只需要给json_encode函数中传入一个参数JSON_UNESCAPED_UNICODE即可,如下:
1 <?php 2 3 $tmpArr = array( 4 ‘name‘ => ‘长裤‘, 5 ‘color‘ => ‘blue‘, 6 ‘size‘ => ‘XL‘, 7 ‘title‘ => ‘中年男装 长裤‘ 8 ); 9 10 $tmpJson = json_encode($tmpArr,JSON_UNESCAPED_UNICODE); 11 12 echo $tmpJson;
输出:{"name":"长裤","color":"blue","size":"XL","title":"中年男装 长裤"}
但是PHP版本<5.4.0中并不支持以上参数JSON_UNESCAPED_UNICODE,可通过以下方式解决
1 $tmpArr = array( 2 ‘name‘ => ‘长裤‘, 3 ‘color‘ => ‘blue‘, 4 ‘size‘ => ‘XL‘, 5 ‘title‘ => ‘中年男装 长裤‘ 6 ); 7 8 $tmpJson = json_encode($tmpArr); 9 $tmpJson = preg_replace_callback("#\\\u([0-9a-f]{4})#i",function($matchs){ 10 return iconv(‘UCS-2BE‘, ‘UTF-8‘, pack(‘H4‘, $matchs[1])); 11 },$tmpJson); 12 13 echo $tmpJson;
输出:{"name":"长裤","color":"blue","size":"XL","title":"中年男装 长裤"}
最后就可以封装一个函数(主要是测试环境跟生产环境不同所以封装一个函数,可以根据自己的PHP环境只用一种方式即可):
1 <?php 2 $tmpArr = array( 3 ‘name‘ => ‘长裤‘, 4 ‘color‘ => ‘blue‘, 5 ‘size‘ => ‘XL‘, 6 ‘title‘ => ‘中年男装 长裤‘ 7 ); 8 9 function json_encode_array($array){ 10 if(version_compare(PHP_VERSION,‘5.4.0‘,‘<‘)){ 11 $str = json_encode($array); 12 $str = preg_replace_callback("#\\\u([0-9a-f]{4})#i",function($matchs){ 13 return iconv(‘UCS-2BE‘, ‘UTF-8‘, pack(‘H4‘, $matchs[1])); 14 },$str); 15 return $str; 16 }else{ 17 return json_encode($array, JSON_UNESCAPED_UNICODE); 18 } 19 } 20 21 echo json_encode_array($tmpArr);
输出:{"name":"长裤","color":"blue","size":"XL","title":"中年男装 长裤"}
标签:call compare 解决 name style mat encode tmp lse
原文地址:https://www.cnblogs.com/yuwenbo/p/9595302.html