PHP------Arrays and objects are converted to each other, StdClass object to array

Source: Internet
Author: User
Tags goto

Array goto JSON

PHP Json_encode () is used to encode the variable JSON, which returns FALSE if the execution succeeds in returning the JSON data.

JSON to Array

The PHP Json_decode () function is used to decode a JSON-formatted string and convert it to a PHP variable.

$arr Array (' A ' = 1, ' b ' = = 2, ' c ' = 3, ' d ' = 4, ' e ' = 5 ');    echo json_encode ($arr);

results:   {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5}

Vice versa.

Third-party interface parsing (StdClass object to array)

Recently, the development of the mall, the use of the logistics of the third-party API interface JSON data, often simply through the Json_decode method to obtain the numerical value is generally not an array,

It is a string of objects with Stdclass objec, and if we want to get the corresponding PHP array, we need to get it in the following ways.

//PHP StdClass Object goto ArrayfunctionObject_array ($array) {      if(Is_object($array)) {          $array= (Array)$array; } if(Is_array($array)) {           foreach($array  as $key=$value) {               $array[$key] = Object_array ($value); }       }       return $array; }

Because the Json_decode () function can accept two parameters:

When $data = Json_decode ($object); //Gets an object above the data type.

When $data = Json_decode ($object, ture); //The array is obtained.

$data= Json_decode ($json, ture);   

I use the second kind, simple also convenient, print data

Print_array ($data);

This is the same as the usual array, but also convenient to use, for example:

Echo $data [' Data '] [0] [' Traces '] [0] [' Desc ']; // [ Shanghai] [jiading] The earthquake emblem electronic received phone: no

PHP------Arrays and objects are converted to each other, StdClass object to array

Related Article

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.