Home > Backend Development > PHP Tutorial > PHP Tips: Use json_encode() to assign values ​​to js arrays

PHP Tips: Use json_encode() to assign values ​​to js arrays

jacklove
Release: 2023-03-27 13:28:01
Original
2395 people have browsed it

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>
Copy after login


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(&#39;Think&#39;,&#39;PHP&#39;,&#39;China&#39;);
JS:
<script>
var myarray={:json_encode($myarr)};  //注意,这里不要用双引号或单引号;
var arr = <!--?php echo json_encode($arr, JSON_PRETTY_PRINT) ?-->;
</script>
Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template