Home > Article > Backend Development > PHP Tips: Use json_encode() to assign values to js arrays
This article explains in detail the relevant content of json_encode() assigning values to js arrays.
1. Cleverly use json_encode() to assign values to js arrays
Many times, we have to pay the results processed by PHP to js for processing. However, when assigning values to js, the assignment of a single variable is relatively simple and easy to implement. Just output the PHP variable directly through the template tag. 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 process the array with PHP When assigning values to an array in js, you will encounter many problems. If you assign a value directly like a single variable, js cannot read each element in the array.
In practical applications, I used the json_encode() function to process PHP arrays. In this way, the PHP-processed arrays can be easily sent to js in json data format. Similarly, js Get an array that is also in json data format. For example:
PHP: $this->myarr=array('Think','PHP','China'); JS: <script> var myarray={:json_encode($myarr)}; //注意,这里不要用双引号或单引号; var arr = <!--?php echo json_encode($arr, JSON_PRETTY_PRINT) ?-->; </script>
At this time, myarray=['Think','PHP','China']; in js is such an array in json format, which is in js Processing is fairly easy in Medium Processing.
With the json_encode() function, you can easily assign PHP arrays to js arrays~
This article explains the relevant content of json_encode() assigning values to js arrays. Please pay attention to more related content. php Chinese website.
Related recommendations:
Features and syntax instructions of PHP and XML technology
Explanation of PHP and Ajax technology
Thinkphp5 Detailed explanation of pre-operations
The above is the detailed content of PHP Tips: Use json_encode() to assign values to js arrays. For more information, please follow other related articles on the PHP Chinese website!