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

PHP:
  1. $my_array = array(1,2,3,4,5);
  2. $my_array2= array('one'=>'1','two'=>'2','3');
  3. $this->set(compact('my_array','my_array2'));

View code

PHP:
  1. echo $javascript->Object($my_array);
  2. echo $javascript->Object($my_array2);

The output is

JavaScript:
  1. [1, 2, 3, 4, 5]
  2. {"one":1, "two":2, "0":3}

A more complex output from the result of findAll in Cheesecake-Photoblog is shown below.

PHP:
  1. (
  2.     [0] => Array
  3.         (
  4.             [Photo] => Array
  5.                 (
  6.                     [id] => 2
  7.                     [filename] => 1180944624_3dgreen.png
  8.                     [title] => 3D Green
  9.                     [created] => 2007-06-04 13:40:00
  10.                 )
  11.  
  12.         )
  13.  
  14.     [1] => Array
  15.         (
  16.             [Photo] => Array
  17.                 (
  18.                     [id] => 1
  19.                     [filename] => 1180938295_FreshFlower.jpg
  20.                     [title] => Fresh Flower
  21.                     [created] => 2007-06-04 11:54:00
  22.                 )
  23.  
  24.         )
  25.  
  26. )

Resultant JSON

JavaScript:
  1. [{"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