search
HomeBackend DevelopmentPHP ProblemHow to convert php array into js array

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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.