Php json converted into an array for code sharing, json Array

Source: Internet
Author: User
Tags php json

Php json converted into an array for code sharing, json Array

The written json is converted into an array class and method. In fact, the writing method can convert most data structures containing json strings into arrays. The Code is as follows:

Copy codeThe 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 to convert all json data.
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 that $ params is an object and can be converted only when its 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 we can use it for the time being. If you have good suggestions, I hope you can discuss and make progress together. Thank you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.