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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
