PHP array to JSON in CakePHP
It is an often asked question on the CakePHP google groups, how to pass a php array to javascript. The answer is to convert the PHP array to JSON, I have seen several solutions recommended which included using vendor classes, the PHP 5 extension for JSON - however the recommended way is to use the 'Object' method of javascript helper. Being a pure PHP solution it works in both PHP 4 as well 5
Using it is as simple as using any other helper, suppose you have some arrays in your controller, just pass them to the view and use.
OK! here is stripped down code snippet with output
Controller code
View code
The output is
-
[1, 2, 3, 4, 5]
-
{"one":1, "two":2, "0":3}
A more complex output from the result of findAll in Cheesecake-Photoblog is shown below.
Resultant JSON
-
[{"Photo":{"id":2, "filename":"1180944624_3dgreen.png", "title":"3D Green", "created":"2007-06-04 13:40:00"}}, {"Photo":{"id":1, "filename":"1180938295_FreshFlower.jpg", "title":"Fresh Flower", "created":"2007-06-04 11:54:00"}}]
What you now do with the JSON output is entirely upto you
About this entry
You’re currently reading “ PHP array to JSON in CakePHP ,” an entry on SANIsoft - PHP for E Biz
- Published:
- 6.4.07 / 5pm
- Category:
- CakePHP, Javascript, PHP
- Author:
- Tarique Sani
1 Comment
Jump to comment form | comments rss | trackback uri