Home  >  Article  >  Backend Development  >  How to convert php array into js array

How to convert php array into js array

藏色散人
藏色散人Original
2021-03-08 09:56:552907browse

How to convert a php array into a js array: 1. Use the foreach statement to traverse the array, with the syntax "foreach($arr as $value){//loop body code}"; 2. In the loop body, pass json_encode() performs json encoding on each value in the array, the syntax is "json_encode($value)"; 3. Use the splicing character "." to add a comma after each compiled value; 4. Add outside all values The "[]" symbol is sufficient.

How to convert php array into js array

#The operating environment of this article: Windows 7 system, PHP8, Dell G3 computer.

JSON usage: Convert PHP array to JS array, how does JS receive PHP array

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 merge it with the js file? Identify?

Let’s look at the php file first. 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 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 after each value is json encoded The comma comes at the end, which results in an extra comma when all the values ​​are merged into the array, so 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 transmitted by the php file

var json = JSON.parse(arr);

JSON is the one we start downloading An object defined in the file, 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!

Conversion between PHP array and Json

The reason why Json is used is often because when using ajax objects, the program and Data interaction between JS functions. Because JS does not recognize arrays in PHP, PHP does not recognize arrays or objects in JS. Json solves this problem very well.

Json Introduction

JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of JavaScript, which means JavaScript can read Json directly, which is very convenient.

The specific form of Json is:

1. Object

The object is an unordered collection of "name/value pairs". An object starts with "{" (left bracket) and ends with "}" (right bracket). Each "name" is followed by a ":" (colon); "name/value" pairs are separated by a "," (comma).

For example: {"username": "Eric","age":23,"sex": "man"}

Code example:

<script type="text/javascript">  function getUser()
{
  var  user = {
  "username": "Eric",
  "age":23,
  "family": {"mother":"Marry","father":"Alon","brother":"Tom"}
  };  alert( user.username );  alert( user.age );  alert(user.family.brother);
}  getUser();  </script>

2, array

An array is an ordered collection of values. An array starts with "[" (left bracket) and ends with "]" (right bracket). Values ​​are separated by "," (comma).

For example: ["Eric",23, "man"]

Code example:

<script type="text/javascript">  function getArray() 
{  
var arr = ["Jarry",23, ["www.xiaophper.com","wxyh_999@126.com"]];  
alert(arr[0]);  alert(arr[1]);  alert(arr[2][0]); 
alert(arr[2][1]);  
}  
getArray();  
</script>

Note: The two forms of objects and arrays are different when called in JS It’s the same, objects are called with “.”, and arrays are called with subscripts [0] and [1]. Also note that string type values ​​must be enclosed in quotes when passing Json strings.

Convert array into Json in PHP

Powerful PHP has provided built-in functions: json_encode() and json_decode(). It is easy to understand that json_encode() converts a PHP array into Json. On the contrary, json_decode() converts Json into a PHP array.

For example:

$array = array("name" => "Eric","age" => 23); 
echo json_encode($array);

The program will print out:

The code is as follows:

{"name":"Eric","age":23}

Look at the following example again:

$array = array(0 => "Eric", 1 => 23); 
echo json_encode($array);

The program will print out: ["Eric",23]

It can be seen from the above two examples that if PHP If the keys of the array are all numbers, then json_encode() returns Json in the form of an array. If the keys of the PHP array are all strings. Then json_encode() will return Json in the form of an object. Just said it. The two calls in js are different.

In fact, as long as there is a key in the form of a string in the key of the PHP array, then json_encode() will return Json in the form of an object. This is not correct. Because, although no errors will occur in the PHP code, if such a Json is passed to a JS function, JS will treat the Json as an object, and it is impossible for an object to use numbers as attribute names. In other words, JS does not know what this is: user.0.username (the middle is the number zero)

[Recommendation: "PHP Video Tutorial"]

The above is the detailed content of How to convert php array into js array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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