This article illustrates the implementation of recursive JSON classes in PHP. Share to everyone for your reference.
The specific implementation code is as follows:
Copy Code code as follows:
<?php
/*
* @ anthor:qd
* @ time:2013-09-27
*/
Class json{
Private $ARR = Array (); Incoming array
Construction device
Public function json ($array)
{
if (!is_array ($array)) return false;
$this->arr = $array;
}
Resolving the main function
Public Function Mainarr ()
{
$arr = $this->arr;
if ($this->typearr ($arr))
{
$json = $this->numarr ($arr);
}
Else
{
$json = $this->indexarr ($arr);
}
return $json;
}
Parsing an array of indices
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;
}
Resolving numeric arrays
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;
}
Verify that an array is not a strict numeric index
Public Function Typearr ($arr)
{
if (array_values ($arr) = = $arr) return true;
return false;
}
}
?>
I hope this article will help you with your PHP program design.