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"}]