Convert PHPJSON to array

Source: Internet
Author: User
Convert PHPJSON to array

  1. $ S = '{"webname": "homehf", "url": "www.homehf.com", "qq": "744348666 "}';

  2. $ Web = json_decode ($ s); // Convert the character to JSON
  3. $ Arr = array ();
  4. Foreach ($ web as $ k =>$ w) $ arr [$ k] = $ w;

  5. The first three rows can be replaced by $ web = json_decode ($ s, true;

  6. Print_r ($ arr );

  7. ?>

In the above code, a JSON object has been converted into an array, but if it is nested JSON, the above code is obviously powerless, then we write a function to solve nested JSON,

  1. Function json_to_array ($ web ){

  2. $ Arr = array ();
  3. Foreach ($ web as $ k => $ w ){
  4. If (is_object ($ w) $ arr [$ k] = json_to_array ($ w); // judge whether the type is an object.
  5. Else $ arr [$ k] = $ w;
  6. }
  7. Return $ arr;
  8. }

  9. $ S = '{"webname": "homehf", "url": "www.homehf.com", "contact": {"qq": "744348666", "mail ": "nieweihf@163.com", "xx": "xxxxxxx "}}';

  10. $ Web = json_decode ($ s );
  11. $ Arr = json_to_array ($ web );

  12. // The previous line can be replaced by $ web = json_decode ($ s, true;

  13. Print_r ($ arr );
  14. ?>

The custom json_to_array () method can convert any nested JSON into an array.

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.