Home >Web Front-end >JS Tutorial >How to assign value to js array in php

How to assign value to js array in php

巴扎黑
巴扎黑Original
2017-08-04 16:58:172515browse

PHP function library provides functions for encoding/decoding JSON: json_encode() and json_decode(), which can more conveniently pass arrays or objects to javascript

Because of the requirements of the interface party, use js to process data , so the PHP program needs to retrieve the value from the database and assign it to the JS array. I haven't found a good way yet, because the data encoding of PHP arrays is different from the encoding format of JS arrays and cannot be output directly.

After searching on the Internet, I found the solution:

The PHP function library provides a function for encoding/decoding JSON: json_encode( ) and json_decode(), which can more conveniently pass arrays or objects to javascript. Note: The JSON extension is only bound to PHP 5.2 and above.

Write as follows in php:

The code is as follows:

$arr = array('1',array('2','3'),array('new','old'));
$new_arr = json_encode($arr);//new_arr的输出结果是;["1",["2","3"],["new","old"]]  
echo "var data =". $new_arr;

After referencing the above php file in the page, directly in js Data can be manipulated.

The above is the detailed content of How to assign value to js array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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