標籤: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":"中年男裝 長褲"}
php中內建函數 json_encode