php數(shù)組轉(zhuǎn)成json格式的方法
本文實(shí)例講述了php數(shù)組轉(zhuǎn)成json格式的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
if( !is_array( $array ) ){
return false;
}
$associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
if( $associative ){
$construct = array();
foreach( $array as $key => $value ){
// We first copy each key/value pair into a staging array,
// formatting each key and value properly as we go.
// Format the key:
if( is_numeric($key) ){
$key = "key_$key";
}
$key = "'".addslashes($key)."'";
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "'".addslashes($value)."'";
}
// Add to staging array:
$construct[] = "$key: $value";
}
// Then we collapse the staging array into the JSON form:
$result = "{ " . implode( ", ", $construct ) . " }";
} else { // If the array is a vector (not associative):
$construct = array();
foreach( $array as $value ){
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "'".addslashes($value)."'";
}
// Add to staging array:
$construct[] = $value;
}
// Then we collapse the staging array into the JSON form:
$result = "[ " . implode( ", ", $construct ) . " ]";
}
return $result;
}
希望本文所述對(duì)大家的php程序設(shè)計(jì)有所幫助。
- php curl獲取到j(luò)son對(duì)象并轉(zhuǎn)成數(shù)組array的方法
- php實(shí)現(xiàn)數(shù)組中索引關(guān)聯(lián)數(shù)據(jù)轉(zhuǎn)換成json對(duì)象的方法
- JSON PHP中,Json字符串反序列化成對(duì)象/數(shù)組的方法
- 淺析C/C++,Java,PHP,JavaScript,Json數(shù)組、對(duì)象賦值時(shí)最后一個(gè)元素后面是否可以帶逗號(hào)
- php數(shù)組轉(zhuǎn)換js數(shù)組操作及json_encode的用法詳解
- php 將json格式數(shù)據(jù)轉(zhuǎn)換成數(shù)組的方法
- PHP實(shí)現(xiàn)數(shù)組轉(zhuǎn)JSon和JSon轉(zhuǎn)數(shù)組的方法示例
- php json轉(zhuǎn)換成數(shù)組形式代碼分享
- PHP自定義遞歸函數(shù)實(shí)現(xiàn)數(shù)組轉(zhuǎn)JSON功能【支持GBK編碼】
- PHP數(shù)組對(duì)象與Json轉(zhuǎn)換操作實(shí)例分析
相關(guān)文章
PHP 使用MySQL管理Session的回調(diào)函數(shù)詳解
本篇文章文章是對(duì)PHP中使用MySQL管理Session的回調(diào)函數(shù)進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06Linux服務(wù)器下PHPMailer發(fā)送郵件失敗的問(wèn)題解決
這篇文章主要給大家介紹了關(guān)于如何解決Linux服務(wù)器下PHPMailer發(fā)送郵件失敗的問(wèn)題,文中通過(guò)示例代碼介紹的很詳細(xì),相信對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-03-03仿AS3實(shí)現(xiàn)PHP 事件機(jī)制實(shí)現(xiàn)代碼
仿AS3實(shí)現(xiàn)PHP 事件機(jī)制實(shí)現(xiàn)代碼,需要的朋友可以參考下。2011-01-01php連接函數(shù)implode與分割explode的深入解析
本篇文章是對(duì)php連接函數(shù)implode與分割explode進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06php實(shí)現(xiàn)求相對(duì)時(shí)間函數(shù)
這篇文章主要介紹了php實(shí)現(xiàn)求相對(duì)時(shí)間函數(shù),可實(shí)現(xiàn)簡(jiǎn)單求相對(duì)時(shí)間為幾分鐘前或幾小時(shí)前的功能,非常簡(jiǎn)單實(shí)用,需要的朋友可以參考下2015-06-06