In PHP, use JSON and restore json to an array. json Array _ PHP Tutorial

Source: Internet
Author: User
In PHP, use JSON to restore json to an array or a json Array. In the PHP language, JSON and json are restored to an array. I wrote a simple example of php returning json data before using the json Array. I just got online and suddenly found an article, json is also introduced. JSON is also used in PHP and json is restored to an array, json Array

I have previously written a simple example of php returning json data. I just got online and suddenly found an article about json, which is quite detailed and worthy of reference. The content is as follows:

Starting from version 5.2, PHP provides native json_encode () and json_decode () functions. The former is used for encoding and the latter is used for decoding.

I. json_encode ()

1234 $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);echo json_encode($arr);?>

Output

1 {"a":1,"b":2,"c":3,"d":4,"e":5}

Let's look at an example of object conversion:

123456 $obj->body = 'another post';$obj->id = 21;$obj->approved = true;$obj->favorite_count = 1;$obj->status = NULL;echo json_encode($obj);

Output

1234567891011 {   "body":"another post",    "id":21,    "approved":true,    "favorite_count":1,    "status":null }

Because json only accepts UTF-8 encoded characters, the json_encode () parameter must be UTF-8 encoded. otherwise, null or null is obtained. Pay special attention to this when Chinese characters use GB2312 encoding or foreign languages use ISO-8859-1 encoding.

2. index array and associated array

PHP supports two types of arrays: one is to save only the index array (indexed array) of "value", and the other is to save "name/value) associated array (associative array ).

Because javascript does not support associating arrays, json_encode () only converts the index array (indexed array) to the array format, and converts the associated array (associative array) to the object format.

For example, there is an index array

123 $arr = Array('one', 'two', 'three'); echo json_encode($arr);

Output

1 ["one","two","three"]

If you change it to an associated array:

123 $arr = Array('1'=>'one', '2'=>'two', '3'=>'three'); echo json_encode($arr);

Output

1 {"1":"one","2":"two","3":"three"}

Note that the data format is changed from "[]" (array) to "{}" (object ).

If you want to forcibly convert an "index array" to "object", you can write

1 json_encode( (object)$arr );

Or

1 json_encode ( $arr, JSON_FORCE_OBJECT );

III. class conversion

The following is a PHP class:

1234567891011121314151617 class Foo {   const ERROR_CODE = '404';   public $public_ex = 'this is public';   private $private_ex = 'this is private!';   protected $protected_ex = 'this should be protected';   public function getErrorCode() {     return self::ERROR_CODE;   } }

Now, perform json conversion on the instance of this class:

12345 $foo = new Foo; $foo_json = json_encode($foo); echo $foo_json;

The output result is

1 {"public_ex":"this is public"}

As you can see, except the public variable, other things (constants, private variables, methods, and so on) are lost.

IV. json_decode ()

This function is used to convert json text to the corresponding PHP Data structure. The following is an example:

12345 $json = '{"foo": 12345}'; $obj = json_decode($json); print $obj->{'foo'}; // 12345

In general, json_decode () always returns a PHP object instead of an array. For example:

123 $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json));

The result is to generate a PHP object:

12345678910 object(stdClass)#1 (5) {   ["a"] => int(1)  ["b"] => int(2)  ["c"] => int(3)  ["d"] => int(4)  ["e"] => int(5) }

If you want to forcibly generate a PHP join array, json_decode () requires a parameter true:

123 $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';   var_dump(json_decode($json,true));

The result generates an associated array:

12345678910 array(5) {   ["a"] => int(1)   ["b"] => int(2)   ["c"] => int(3)   ["d"] => int(4)   ["e"] => int(5) }

5. common errors of json_decode ()

The three json statements below are all incorrect. can you tell where the error is?

12345 $bad_json = "{ 'bar': 'baz' }"; $bad_json = '{ bar: "baz" }'; $bad_json = '{ "bar": "baz", }';

If json_decode () is executed on these three strings, null is returned and an error is returned.

The first error is that the json separator (delimiter) only allows double quotation marks and does not support single quotation marks. The second error is the "name" of the json name-value pair (the part on the left of the colon). double quotation marks must be used in any case. The third error is that you cannot add a comma (trailing comma) after the last value ).

In addition, json can only be used to represent objects and arrays. if json_decode () is used for a string or value, null is returned.

1 var_dump(json_decode("Hello World")); //null

Ghost previously wrote a simple example of php returning json data. I just got online and suddenly found an article about json...

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.