php json Convert to Array Code Sharing
- 2021-07-26 07:08:51
- OfStack
Write json into an array of 1 class and method, actually write the method can contain most of the json string data structure into an array, on the code:
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;
}
// Calls this method, containing the json The data of 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 1 Next, if $params Yes 1 Objects that only contain properties that are readable ( public Or temporary object properties)
elseif(is_object($params))
$tmp = self::stdClassToArray($params);
else
$tmp = $params;
return $tmp;
}
The above is related to the code, at least the time you can still get it, if you have good suggestions, I hope you can discuss and make progress together, thank you