Use JavaScript helper in CakePHP to convert the PHP array to JSON

Source: Internet
Author: User
Tags php array to json

A frequently asked question in Google groups is: how to pass a PHP array
Javascript. The answer is to convert the PHP array to JSON. There are several solutions: including third-party PHP
Class Library, PhP5 JSON extension (php_json.dll or JSON. So ).
However, the recommended method is to use JavaScript helper of CakePHP as a pure PHP Solution.
It works on both PhP4 and PhP5.

Using it is as simple as using other helper. Suppose there are some arrays in your controller and pass them
The view can be used.

Okay. Here are some code snippets and outputs.

Controller code (PHP ):

$ My_array = array (1, 2, 3, 4, 5 );
$ My_array2 = array ('one' => '1', 'two' => '2', '3 ');
$ This-> set (COMPACT ('My _ array', 'My _ array2 '));

View code (PHP ):

Echo $ JavaScript-> Object ($ my_array );
Echo $ JavaScript-> Object ($ my_array2 );

The output is (JavaScript ):

[1, 2, 3, 4, 5]
{"One": 1, "two": 2, "0": 3}


The output result of the more complex cheesecake-photoblog findall method is as follows (PHP ):

Array
(
[0] => Array
(
[Photo] => Array
(
[ID] => 2
[Filename] => 1180944624_3dgreen.png
[Title] => 3D Green
[Created] => 13:40:00
)
)

[1] => Array
(
[Photo] => Array
(
[ID] => 1
[Filename] => 1180938295_freshflower.jpg
[Title] => fresh flower
[Created] => 11:54:00
)
)
)

JSON result:

[{"Photo": {"ID": 2, "FILENAME": "1180944624_3dgreen.png", "title": "3D Green", "created ": "13:40:00" }}, {"photo": {"ID": 1, "FILENAME": "1180938295_freshflower.jpg", "title": "Fresh Flower", "created ": "11:54:00"}]

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.