Home > Backend Development > PHP Problem > How to convert php array to js array object

How to convert php array to js array object

coldplay.xixi
Release: 2023-03-06 07:54:01
Original
2622 people have browsed it

How to convert php array to js array object: first get the [$arr] array; then use the function [json_encode()] to json encode each value of the array; then output a json array; finally use arr accepts an array.

How to convert php array to js array object

##Related learning recommendations: js video tutorial

How to convert php array to js array object:

First look at the php file. When we get the $arr array

foreach ($arr as $value) {
    $json .= json_encode($value) . ',';
} 
echo '[' . substr($json,0,strlen($json) - 1) . ']';
Copy after login

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 '[ outside all values ]', 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, so we have to use substr() The function removes its last comma!

Then let’s look at the js file

When we use arr to receive the json array transmitted by the php file

var json = JSON.parse(arr);
Copy after login

JSON is an object defined in the file we start 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!

If you want to learn more about programming, please pay attention to the php training column!

The above is the detailed content of How to convert php array to js array object. 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