本文實(shí)例講述了PHP自定義遞歸函數(shù)實(shí)現(xiàn)數(shù)組轉(zhuǎn)JSON功能。分享給大家供大家參考,具體如下:
問題:
由于最近的一個(gè)項(xiàng)目中要給別的公司提供接口,給他們喂 GBK 編碼的 json 數(shù)據(jù),但是有一個(gè)問題是 PHP 中的 json_encode
加密函數(shù)只支持 utf-8 編碼,這就比較尷尬了。我們的數(shù)據(jù)是 GBK 編碼的,接收方要求的數(shù)據(jù)格式也是 GBK 編碼的,一開始想的是先將數(shù)據(jù)轉(zhuǎn)為 utf-8 編碼再使用 json_encode
函數(shù),結(jié)果是這導(dǎo)致我們的中文內(nèi)容亂碼了,所以,最后使用的是手動(dòng)對(duì)數(shù)據(jù)加密的方式。
實(shí)現(xiàn):
想實(shí)現(xiàn)這個(gè)功能,最主要是觀察 json 數(shù)據(jù)的特點(diǎn),一開始 LZ 總結(jié)得不到位導(dǎo)致不能完全實(shí)現(xiàn) json_encode
函數(shù)的功能,后面參照網(wǎng)上的資料,實(shí)現(xiàn)了這個(gè)功能(就是一個(gè)遞歸函數(shù)):
function newArrayToJson($array)
{
if(!is_array($array))
{
return '';
}
$func = __FUNCTION__;
//關(guān)鍵判斷是不是關(guān)聯(lián)數(shù)組,以此來決定是否需要json加密key和使用[]
$associative = (array_keys($array) !== range(0, count($array) - 1)) ? true : false;
if($associative !empty($array))
{
$construct = array();
foreach($array as $key => $value)
{
$key = '"'.$key.'"';
if(is_array($value))
{
$value = $func($value);
}
elseif(!is_numeric($value))
{
$value = '"'.$value.'"';
}
$construct[] = "$key:$value";
}
$result = "{".implode(",",$construct)."}";
}
else
{
$construct = array();
foreach($array as $value)
{
if(is_array($value))
{
$value = $func($value);
}
else if(!is_numeric($value))
{
$value = '"'.$value.'"';
}
$construct[] = $value;
}
$result = "[".implode(",", $construct)."]";
}
return $result;
}
//測(cè)試:
$arr=array('1'=>'www.jb51.net','2'=>'www.baidu.com','3'=>'www.sina.com.cn','4'=>'腳本之家');
echo newArrayToJson($arr);
/*
運(yùn)行結(jié)果:
{"1":"www.jb51.net","2":"www.baidu.com","3":"www.sina.com.cn","4":"腳本之家"}
*/
PS:這里再為大家推薦幾款比較實(shí)用的json在線工具供大家參考使用:
在線JSON代碼檢驗(yàn)、檢驗(yàn)、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在線格式化工具:
http://tools.jb51.net/code/jsonformat
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉(zhuǎn)換工具:
http://tools.jb51.net/code/jsoncodeformat
C語言風(fēng)格/HTML/CSS/json代碼格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP中json格式數(shù)據(jù)操作技巧匯總》、《PHP數(shù)學(xué)運(yùn)算技巧總結(jié)》、《PHP基本語法入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- JavaScript遞歸函數(shù)定義與用法實(shí)例分析
- JavaScript遞歸函數(shù)解“漢諾塔”算法代碼解析
- 基于JS遞歸函數(shù)細(xì)化認(rèn)識(shí)及實(shí)用實(shí)例(推薦)
- JavaScript正則表達(dá)式校驗(yàn)與遞歸函數(shù)實(shí)際應(yīng)用實(shí)例解析
- JS中遞歸函數(shù)
- javascript中遞歸函數(shù)用法注意點(diǎn)
- javascript實(shí)現(xiàn)網(wǎng)頁子頁面遍歷回調(diào)的方法(涉及 window.frames、遞歸函數(shù)、函數(shù)上下文)
- js中遞歸函數(shù)的使用介紹
- javascript 用記憶函數(shù)快速計(jì)算遞歸函數(shù)
- javascript遞歸函數(shù)定義和用法示例分析