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

How to assign value to js array in php_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:56:201233browse

Due to the requirements of the interface party, the data is processed in js, so the php program needs to retrieve the values ​​​​from the database and assign them 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 online, I found the solution:

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

Write the following in php:

Copy the code The code is as follows:

$arr = array('1',array('2','3'),array('new','old'));
$new_arr = json_encode($arr);//new_arr The output result is;["1",["2","3"],["new","old"]]
echo "var data =". $new_arr;

After referencing the above php file in the page, the data can be directly operated in js.
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