PHP uses JSON and restores JSON to an array of _php instances

Source: Internet
Author: User

Before I wrote a simple example of PHP return JSON data, just surf the internet, suddenly found an article, also introduced JSON, quite detailed, it is worth reference. The contents are as follows

Starting with version 5.2, PHP native provides Json_encode () and Json_decode () functions, which are used for encoding and decoding.

One, Json_encode ()

Copy Code code as follows:

<?php
$arr = Array (' A ' =>1, ' B ' =>2, ' C ' =>3, ' d ' =>4, ' e ' =>5);
echo Json_encode ($arr);
?>

Output

Copy Code code as follows:

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

Let's look at an example of an object conversion:

Copy Code code as follows:

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

Output

[/code]
{
"Body": "Another Post",
"id": 21,
"Approved": TRUE,
"Favorite_count": 1,
' Status ': null
}
[/code]

Since JSON only accepts UTF-8 encoded characters, the Json_encode () argument must be utf-8 encoded, or it will get null characters or NULL. Special attention should be paid to the use of GB2312 encoding in Chinese, or the use of iso-8859-1 encoding in foreign languages.

index arrays and associative arrays

PHP supports two types of arrays, one is the index array (indexed array) that holds only the value, the other is an associative array (associative array) that holds the name value pair (name/value).

Because JavaScript does not support associative arrays, json_encode () only converts an indexed array (indexed array) into an array format and an associative array (associative array) into object format.

For example, now there is an array of indices

Copy Code code as follows:

$arr = Array (' One ', ' two ', ' three ');
echo Json_encode ($arr);

Output

Copy Code code as follows:

["One", "two", "three"]

If you change it to an associative array:

Copy Code code as follows:

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

Output into

Copy Code code as follows:

{"1": "One", "2": "Two", "3": "Three"}

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

If you need to force an "indexed array" into an "object", you can write

Copy Code code as follows:

Json_encode ((object) $arr);

Or

Copy Code code as follows:

Json_encode ($arr, json_force_object);

Classes (Class) conversion

The following is a class of PHP:

Copy Code code as follows:

Class Foo {
Const Error_code = ' 404 ';
Public $public _ex = ' it is public ';
Private $private _EX = ' this is private! ';
protected $protected _EX = ' This should to be protected ';
Public Function GetErrorCode () {
return self::error_code;
}
}

Now, make a JSON conversion to an instance of this class:

Copy Code code as follows:

$foo = new Foo;
$foo _json = Json_encode ($foo);
echo $foo _json;

The output result is

Copy Code code as follows:

{' PUBLIC_EX ': ' This is public '}

As you can see, other things (constants, private variables, methods, and so on) are lost in addition to exposing variables (public).

Iv. Json_decode ()

This function is used to convert JSON text to the appropriate PHP data structure. Here is an example:

Copy Code code as follows:

$json = ' {' foo ': 12345} ';
$obj = Json_decode ($json);
Print $obj->{' foo '}; 12345

Typically, Json_decode () always returns a PHP object, not an array. Like what:

Copy Code code as follows:

$json = ' {' A ': 1, "B": 2, "C": 3, "D": 4, "E": 5} ';
Var_dump (Json_decode ($json));

The result is to generate a PHP object:

Copy Code code as follows:

Object (StdClass) #1 (5) {
["a"] => int (1)
["B"] => int (2)
["C"] => int (3)
["D"] => int (4)
["E"] => int (5)
}

If you want to force a PHP associative array to be generated, json_decode () needs to add a parameter true:

Copy Code code as follows:

$json = ' {' A ': 1, "B": 2, "C": 3, "D": 4, "E": 5} ';
Var_dump (Json_decode ($json, true));

As a result, an associative array is generated:

Copy Code code as follows:

Array (5) {
["a"] => int (1)
["B"] => int (2)
["C"] => int (3)
["D"] => int (4)
["E"] => int (5)
}

V. Common errors in Json_decode ()

The following three kinds of JSON are all wrong, can you see what's wrong?

Copy Code code as follows:

$bad _json = "{' Bar ': ' Baz '}";
$bad _json = ' {bar: ' Baz '} ';
$bad _json = ' {' bar ': ' Baz ',} ';

Performing Json_decode () on these three strings will return null and have an error.

The first error is that the JSON delimiter (delimiter) only allows double quotes and cannot use single quotes. The second error is the name of the JSON name value pair (the part to the left of the colon), which must be used in double quotes in any case. The third error is that a comma (trailing comma) cannot be added after the last value.

In addition, JSON can only be used to represent objects (object) and Arrays (array), and null will be returned if Json_decode () is used for a string or numeric value.

Copy Code code as follows:

Var_dump (Json_decode ("Hello World")); Null

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.