Home > Article > Backend Development > Convert php array to js array, how js receives PHP array, usage of json, jsjson_PHP tutorial
First download the following file (this is a paragraph written by others to specifically parse json code) and then import this file!
http://pan.baidu.com/s/1dD8qVr7
Now when we need to use ajax to interact with the background, how to transfer the php array to the js file and have it recognized by js?
First look at the php file, when we get the $arr array
<span>foreach</span> (<span>$arr</span> <span>as</span> <span>$value</span><span>) { </span><span>$json</span> .= json_encode(<span>$value</span>) . ','<span>; } </span><span>echo</span> '[' . <span>substr</span>(<span>$json</span>,0,<span>strlen</span>(<span>$json</span>) - 1) . ']';
json_encode() is to json encode each value of $arr, and then we want to output a json array, so we add a comma after each compiled value and finally add all Add '[]' outside the value. This is the format of the json array. Note that because we add a comma after each value is json encoded, this will result in an extra comma when all values are merged into the array. All We have to use the substr() function to remove the last comma!
Then let’s look at the js file
When we use arr to receive the json array of php file transfer
<span>var</span> json = JSON.parse(arr);
JSON is an object defined in the file we started downloading. We use its parse method to convert the json array into a js array! This is the variable json that receives a js array, so it cannot be printed directly. You can traverse the json array or json[0] to output!
In fact, to put it bluntly, our idea of converting a php array into a js array is to use the intermediate quantity of json to achieve it! Of course, you can also use only php and js to convert the array, there is more than one method!
Please indicate the source for reprinting: http://www.ly89.cn/detailB/44.html