JavaScript Object symbol of php (JSON)

Source: Internet
Author: User
The JavaScript Object symbol (JSON) of PHP extensions starts with PHP 5.2.0. JSON extensions are built in and compiled into PHP by default.

JSON serialization interface JsonSerializable

Classes that implement JsonSerializable can customize their JSON representation in json_encode.

JsonSerializable: jsonSerialize-specifies the data to be serialized into JSON

Example #1 returns an array

 array = $array;        }        public function jsonSerialize() {            return $this->array;        }    }    $array = [1, 2, 3];    echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);?>

The above routine will output:

[    1,    2,    3]

Example #2 returns an associated array

 array = $array;        }        public function jsonSerialize() {            return $this->array;        }    }    $array = ['foo' => 'bar', 'quux' => 'baz'];    echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);?>

The above routine will output:

{    "foo": "bar",    "quux": "baz"}

Example #3 returns an integer.

 number = (integer) $number;        }        public function jsonSerialize() {            return $this->number;        }    }    echo json_encode(new IntegerValue(1), JSON_PRETTY_PRINT);?>

The above routine will output:

1

Example #4 returns a string

 string = (string) $string;        }        public function jsonSerialize() {            return $this->string;        }    }    echo json_encode(new StringValue('Hello!'), JSON_PRETTY_PRINT);?>

The above routine will output:

"Hello! "

JSON Functions

Json_decode-encode strings in JSON format

Json_encode-JSON encoding of variables

Json_last_error_msg-Returns the error string of the last json_encode () or json_decode () call

Json_last_error-return the final error

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.