Home > php教程 > php手册 > 在CakePHP中利用Javascript Helper把PHP数组转换为JSON

在CakePHP中利用Javascript Helper把PHP数组转换为JSON

WBOY
Release: 2016-06-06 19:51:12
Original
1462 people have browsed it

在Google Groups中一个经常问到的问题是:如何把一个PHP数组传递给 Javascript.答案是把PHP数组转换为JSON,有几个解决办法:包括第三方PHP 类库,PHP5 JSON扩展(php_json.dll 或则 json.so). 但是推荐的方法是使用CakePHP的javascript Helper.作为一个纯PHP的解

 在Google Groups中一个经常问到的问题是:如何把一个PHP数组传递给
Javascript.答案是把PHP数组转换为JSON,有几个解决办法:包括第三方PHP
类库,PHP5 JSON扩展(php_json.dll 或则 json.so).
但是推荐的方法是使用CakePHP的javascript Helper.作为一个纯PHP的解决方法
它能够同时在PHP4和PHP5上工作

使用它像使用其他Helper一样简单,假设在你的控制器中有一些数组,把它们传递给
视图就可使用了.

好了,下面是一些代码片段和输出

控制器代码(PHP):     

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

视图代码(PHP):     

echo $javascript->Object($my_array);
echo $javascript->Object($my_array2);

输出为(Javascript):

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


更复杂的Cheesecake-Photoblog findAll方法的输出结果如下(PHP): 

      Array
      (
          [
0=> Array
              (
                  [Photo] 
=> Array
                      (
                          [id] 
=> 2
                          [filename] 
=> 1180944624_3dgreen.png
                          [title] 
=>
 3D Green
                          [created] 
=> 2007-06-04 13:40:00

                      )
              )
       
          [
1=> Array
              (
                  [Photo] 
=> Array
                      (
                          [id] 
=> 1
                          [filename] 
=> 1180938295_FreshFlower.jpg
                          [title] 
=>
 Fresh Flower
                          [created] 
=> 2007-06-04 11:54:00

                      )
              )
      )

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template