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!