默认情况下php的 json_decode 方法会把特殊字符进行转义,还会把中文转为Unicode编码形式。
这使得数据库查看文本变得很麻烦。所以我们需要限制对于中文的转义。
对于PHP5.4+版本,json_decode函数第二个参数,可以用来限制转义范围。
要限制中文,使用JSON_UNESCAPED_UNICODE参数。
json_encode($a, JSON_UNESCAPED_UNICODE);
例如:在保存数组中中文对应的分数时,其中包含有中文,在将数组转换成字符串json_encode()时,加入参数
JSON_UNESCAPED_UNICODE,就可以防止中文数据被转义。
$answer_score[0] = array("中文1" => mt_rand(95,99));//中文名称对应的分数 $answer_score[1] = array("中文2" => mt_rand(81,87)); $answer_score[2] = array("中文3" => mt_rand(70,80)); $answer_score[3] = array("中文4" => mt_rand(70,80)); $answer_score[4] = array("中文5" => mt_rand(70,80)); $json_answer_score = (json_encode($answer_score , JSON_UNESCAPED_UNICODE)); $model = new SweepstakesModel(); $selfAnswer = $model->updateGroupxzSelfanswer("pengjun123" , "werwef" , $json_answer_score , "军军");
在数据库中存储的结果如下:
Array ( [id] => 1 [openid] => pengjun123 [nickname] => 彭军 [icon] => http://wx.qlogo.cn/mmopen/qhDbvnE5DMn5stSjg52mmB4Tj1nMVCticRShFfBriaE8lAsF3cgzNtZGogVJXUyUOG1W6hQKFWBM8SZhEnIrTyb8LO1nc6sgQd/0 [answer] => werwef [addtime] => 2017-08-15 18:24:22 [subtime] => 2017-08-28 12:13:58 [answer_score] => [{"中文1":95},{"中文2":82},{"中文3":72},{"中文4":76},{"中文5":70}] [answer_point] => 军军 [extend] => 1 [help_answer_score] => [helppositionName] => )
如果不使用 JSON_UNESCAPED_UNICODE , 则会出现如下的转义效果
Array ( [id] => 1 [openid] => pengjun123 [nickname] => 彭军 [icon] => http://wx.qlogo.cn/mmopen/qhDbvnE5DMn5stSjg52mmB4Tj1nMVCticRShFfBriaE8lAsF3cgzNtZGogVJXUyUOG1W6hQKFWBM8SZhEnIrTyb8LO1nc6sgQd/0 [answer] => werwef [addtime] => 2017-08-15 18:24:22 [subtime] => 2017-08-28 12:21:19 [answer_score] => [{"u4e2du65871":98},{"u4e2du65872":87},{"u4e2du65873":77},{"u4e2du65874":79},{"u4e2du65875":78}] [answer_point] => 军军 [extend] => 1 [help_answer_score] => [helppositionName] => )
这种转义之后的数据在数据库很难阅读