- 相關(guān)推薦
PHP如何遞歸實(shí)現(xiàn)json類
PHP如何遞歸實(shí)現(xiàn)json類呢?下面是小編給大家提供的實(shí)現(xiàn)方法,大家可以參考閱讀,更多詳情請(qǐng)關(guān)注應(yīng)屆畢業(yè)生考試網(wǎng)。
代碼如下:
<?php
/*
* @ anthor:QD
* @ time: 2013-09-27
*/
class json{
private $Arr = array(); //傳入數(shù)組
//構(gòu)造器
public function json($array)
{
if(!is_array($array)) return false;
$this->Arr = $array;
}
//解析主函數(shù)
public function MainArr()
{
$arr = $this->Arr;
if($this->TypeArr($arr))
{
$json = $this->NumArr($arr);
}
else
{
$json = $this->IndexArr($arr);
}
return $json;
}
//解析索引數(shù)組
public function IndexArr($arr)
{
$str ="";
foreach($arr as $k=>$value)
{
if(is_array($value))
{
if($this->TypeArr($value)) { $sun=$this->NumArr($value);}
else {$sun=$this->IndexArr($value);}
if(strpos($sun,"}") || strpos($sun,"]"))
{
$str .= """.$k."":".$sun.",";
}
else
{
$str .= """.$k."":"".$sun."",";
}
}
else
{
$str .= """.$k."":"".$value."",";
}
}
$str = "{".trim($str,",")."}";
return $str;
}
//解析數(shù)字?jǐn)?shù)組
public function NumArr($arr)
{
$str = "";
foreach($arr as $value)
{
if(is_array($value))
{
if($this->TypeArr($value)) { $sun=$this->NumArr($value);}
else {$sun=$this->IndexArr($value);}
if(strpos($sun,"}") || strpos($sun,"]"))
{
$str .= $sun.",";
}
else
{
$str .= """.$sun."",";
}
}
else
{
$str .= """.$value."",";
}
}
$str = "[".trim($str,",")."]";
return $str;
}
//檢驗(yàn)一個(gè)數(shù)組是不是嚴(yán)格數(shù)字索引
public function TypeArr($arr)
{
if(array_values($arr) === $arr) return true;
return false;
}
}
?>
【PHP如何遞歸實(shí)現(xiàn)json類】相關(guān)文章:
JavaScript如何實(shí)現(xiàn)JSON.stringify09-19
PHP遞歸效率分析08-25
PHP中多態(tài)如何實(shí)現(xiàn)09-04
如何實(shí)現(xiàn)java漢諾塔遞歸算法09-20
php如何實(shí)現(xiàn)驗(yàn)證碼06-13
PHP中如何實(shí)現(xiàn)crontab代碼05-30
如何實(shí)現(xiàn)PHP圖片裁剪與縮放07-13
PHP實(shí)現(xiàn)RSA加密類的實(shí)例解析08-23
php遞歸遍歷多維數(shù)組的方法10-06