Home >Backend Development >PHP Tutorial >Code sharing for converting php json into array form, json array_PHP tutorial
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:
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;
}