This article mainly introduces the implementation method of PHP recursive JSON class, can realize the parsing of index array and numeric array, and then realize the function of recursive array to return JSON string.
The specific implementation code is as follows:
<?PHP/** @ anthor:qd * @ time:2013-09-27*/ classjson{Private $ARR=Array();//incoming Array//constructor Public functionJson$array) { if(!Is_array($array))return false; $this->arr =$array; } //Parse main function Public functionMainarr () {$arr=$this-ARR; if($this->typearr ($arr)) { $json=$this->numarr ($arr); } Else { $json=$this->indexarr ($arr); } return $json; } //parsing an indexed array Public functionIndexarr ($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; } //parsing a numeric array Public functionNumarr ($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; } //Verify that an array is not strictly numeric indexed Public functionTypearr ($arr) { if(array_values($arr) ===$arr)return true; return false; } } ?>
PHP recursive JSON class instance code