Home >Backend Development >PHP Tutorial >Code sharing for converting php json into array form, json array_PHP tutorial

Code sharing for converting php json into array form, json array_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:14:29822browse

Code sharing for converting php json into array form, json array

is a class and method written to convert json into an array. In fact, the method written can convert most data structures containing json strings into arrays. The above code:

Copy code The code is as follows:

class antiTranJson
{
protected static function jsonToArray($json)
{
If(!is_string($json) || is_null(json_decode($json, true)))
Throw new NotJsonStringException('param is not a json string');
$deJson = json_decode($json, true);
Return self::toArray($deJson);
}

protected static function stdClassToArray($stds)
{
If(is_object($stds))
Throw new NotObjectException('params not object');
$params = get_object_vars($stds);
Return self::toArray($params);
}

protected static function arrayRToArray($params)
{
$tmp = array();
If(!is_array($params))
         throw new NotArrayException('params not array');
foreach($params as $k=>$v)
{
        $tmp[$k] = self::toArray($v);
}
//var_dump($tmp);
Return $tmp;
}

//Call this method, and all data containing json can be converted
public static function toArray($params)
{
$tmp = array();
If(is_string($params) && !is_null(json_decode($params)))
         $tmp = self::jsonToArray($params);
elseif(is_array($params))
         $tmp = self::arrayRToArray($params);
//Note here, if $params is an object, conversion can only be achieved when the included attributes are readable (public or temporary object attributes)
​ elseif(is_object($params))
         $tmp = self::stdClassToArray($params);
else
$tmp = $params;
Return $tmp;
}


The above is the relevant code. At least it is still available for current use. If you have any good suggestions, I hope you can discuss them and make progress together. Thank you

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/909345.htmlTechArticlephp json converted into array form code sharing, json written in json array is converted into a class and method of array, actual The method written above can convert most data structures containing json strings...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn