This article detailed the Json_encode () to the JS array assignment related content.
1. Use Json_encode () to assign a value to the JS array
Most of the time, we have to pay the PHP processing results to JS to deal with. However, when assigning a value to JS, the assignment of a single variable is simple and easy to implement, as long as the template tag directly output PHP variables. For example:
PHP: $this->title= ' I love thinkphp '; Js:<script>var title= "{$title}";</script>
In this way, the $title value of the PHP variable can be processed in JS ~
However, when we assign the array of PHP processing to an array of JS, we encounter a lot of problems. If you assign a value directly like a single variable, JS cannot read the elements in the array.
In the actual application, I used the json_encode () This function to work with the PHP array, so that the PHP processing can be easily processed in the array, in JSON data format to the JS, as well, JS is also a JSON data format array. For example:
PHP: $this->myarr=array (' Think ', ' php ', ' China '); Js:<script>var Myarray={:json_encode ($myarr)}; Note, do not use double or single quotes here; var arr = <!--? php echo json_encode ($arr, json_pretty_print)?-->;</script>
This time, JS in the myarray=[' Think ', ' PHP ', ' China '; Such a JSON-formatted array, which is handled in JS is fairly easy to handle.
Using the Json_encode () function, you can easily assign a PHP array to the JS array ~
This article explains the Json_encode () to the JS array assignment related content, more relevant content please pay attention to the PHP Chinese network.