This article mainly introduces the usage of JSON to convert PHP arrays to JS arrays. For details about how JS receives PHP arrays, refer
This article mainly introduces the usage of JSON to convert PHP arrays to JS arrays. For details about how JS receives PHP arrays, refer
First download the following file (this is a code written by someone else to parse json), and then introduce this file!
Now, when we need to use ajax to interact with the background, how can we transmit php arrays to js files and identify them by js?
First read the PHP file. When we get the $ arr array
Foreach ($ arr as $ value) {$ json. = json_encode ($ value ). ',';} echo '['. substr ($ json, 0, strlen ($ json)-1 ). ']';
Json_encode () is to encode every value of $ arr in json format, and then we want to output a json array, therefore, we add a comma after each compiled value and add '[]' to all values. This is the format of the json array, note that a comma is added after each value is encoded in json format, which leads to an additional comma when all values are merged into the array. substr () is used for all values () remove the last comma from the function!
Then let's look at the js file.
After we use arr to receive the json array transmitted to the PHP file
Var json = JSON. parse (arr );
JSON is an object defined in the file we downloaded. We use its parse method to convert the json array into an array of js! This variable json receives a js array, so it cannot be printed directly. You can traverse this json array or json [0] to output it!
In fact, the idea of converting a php array into a js array is to use the intermediate volume of json! Of course, you can also use php and js to convert arrays. There are more than one method!
Conversion between PHP arrays and Json
Json is often used because of data interaction between programs and JS functions when ajax objects are used. Because JS does not know arrays in PHP, PHP does not know arrays or objects in JS. Json solves this problem.
Introduction to Json
JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of JavaScript, which means JavaScript can directly read Json, which is very convenient.
The Json format is as follows:
1. Object
An object is an unordered set of 'name/value' pairs. An object starts with "{" (left parenthesis) and ends with "}" (right Parenthesis. Each "name" is followed by a ":" (colon); "," (comma) is used to separate the "name/value" pairs.
Example: {"username": "Eric", "age": 23, "sex": "man "}
Sample Code: