要把數一個數組,存到資料庫的一個欄位中,有兩種方法,一種是用序列化函數serialize($arr);還有一種是用php的json擴充內建的函數json_encode($arr);如果json_encode對含有中文的字元進行編碼時,會自動轉換成unicode編碼。就像這樣:a:2:{s:4:”code”;s:1:”1″;s:3:”msg”;s:9:”PHP日誌”;},雖然js上能正常處理,但是看起來還是不那爽,在PHP的官方網站上面找到一個函數,可以解決這個問題,也就是將資料轉換json,而且中文不會被轉換為unicode碼。
| 代碼如下 |
複製代碼 |
<?php function php2js($a=false) { if (is_null($a)) return 'null'; if ($a === false) return 'false'; if ($a === true) return 'true'; if (is_scalar($a)) { if (is_float($a)) { // Always use "." for floats. $a = str_replace(",", ".", strval($a)); }
// All scalars are converted to strings to avoid indeterminism. // PHP's "1" and 1 are equal for all PHP operators, but // JS's "1" and 1 are not. So if we pass "1" or 1 from the PHP backend, // we should get the same result in the JS frontend (string). // Character replacements for JSON. static $jsonReplaces = array(array("", "/", "n", "t", "r", "b", "f", '"'), array('\', '/', 'n', 't', 'r', 'b', 'f', '"')); return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"'; } $isList = true; for ($i = 0, reset($a); $i < count($a); $i++, next($a)) { if (key($a) !== $i) { $isList = false; break; } } $result = array(); if ($isList) { foreach ($a as $v) $result[] = php2js($v); return '[ ' . join(', ', $result) . ' ]'; } else { foreach ($a as $k => $v) $result[] = php2js($k).': '.php2js($v); return '{ ' . join(', ', $result) . ' }'; } } ?> |
使用方法一:
echo serialize(array(‘code’=>’1′,’msg’=>’PHP日誌’));
輸出:a:2:{s:4:”code”;s:1:”1″;s:3:”msg”;s:9:”PHP日誌”;}
使用方法二:
echo json_encode(array(‘code’=>’1′,’msg’=>’PHP日誌’));
輸出:{“code”:”1″,”msg”:”PHPu65e5u5fd7″}
使用方法三:
echo php2js(array(‘code’=>’1′,’msg’=>’未知錯誤’));
輸出:{ “code”: “1”, “msg”: “PHP日誌” }