Method to assign a value to a js array in PHP


Because the interface side of the requirements, with js data processing, so the need for PHP program from the database after the value assigned to the js array. I have not found a good way, because the data encoding of the PHP array and the encoding format of the JS array are not the same, can not be directly output.

After a search on the Internet, the solution was found:

The PHP library provides functions for encoding/decoding JSON: json_encode() and json_decode(), which make it easy to pass arrays or objects to javascript. Note: JSON extensions are only bound to PHP beyond 5.2.

**Write in PHP as follows: **

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

After referring to the above PHP file in the page, js can directly operate on the data.