Home Backend Development PHP Problem How to convert json to array in php

How to convert json to array in php

Apr 27, 2023 am 09:01 AM

JSON (JavaScript Object Notation) is a lightweight data exchange format commonly used for data interaction between web applications. In PHP, we often need to convert JSON format data into arrays for processing. This article will introduce in detail how to convert JSON to an array in PHP.

1. PHP built-in function json_decode()

There is a built-in function json_decode() in PHP that can convert a JSON format string into a PHP array. The syntax of this function is as follows:

mixed json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] )
Copy after login

Among them, the parameter $json represents the JSON string to be decoded; the parameter $assoc defaults to FALSE, indicating that an object is returned instead of an array; the parameter $depth represents the maximum depth of decoding; The parameter $options represents decoding options.

The following is a simple example to convert a JSON string into an array:

<?php
// JSON字符串
$json = &#39;{"name":"Tom","age":18,"hobbies":["reading","writing","swimming"]}&#39;;

// 将JSON字符串转换为数组
$arr = json_decode($json, true);

// 输出数组
print_r($arr);
?>
Copy after login

The output result is:

Array (
    [name] => Tom
    [age] => 18
    [hobbies] => Array (
        [0] => reading
        [1] => writing
        [2] => swimming
    )
)
Copy after login

2. PHP handles JSON parsing errors

However, in actual development, sometimes we encounter JSON parsing errors, such as format errors, data type mismatches and other issues. At this time, we can handle it in the following two ways:

  1. Use try-catch to catch exceptions

You can use try-catch statements in PHP to catch exceptions and execute them. deal with. When the json_decode() function parses a JSON string, it will throw an exception if the format is incorrect or there are other errors. We can use try-catch to catch these exceptions and handle them.

<?php
// JSON字符串
$json = &#39;{"name":"Tom","age":18,"hobbies":}&#39;; // 格式错误

// 将JSON字符串转换为数组
try {
    $arr = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
    print_r($arr);
} catch (JsonException $e) {
    echo "JSON字符串格式错误:" . $e->getMessage();
}
?>
Copy after login

The output result is: JSON string format error: Syntax error

  1. Use the json_last_error() function to obtain error information

In addition to catching exceptions, You can also use the json_last_error() function to get error information when parsing a JSON string. This function returns an integer representing the error code of the last JSON parse. For example, when the format of the parsed JSON string is incorrect, the json_last_error() function will return JSON_ERROR_SYNTAX. We can judge whether the parsing is successful based on the error code and handle it accordingly.

The following is an example:

<?php
// JSON字符串
$json = &#39;{"name":"Tom","age":18,"hobbies":}&#39;; // 格式错误

// 将JSON字符串转换为数组
$arr = json_decode($json, true);

// 判断是否解析成功
if (json_last_error() == JSON_ERROR_NONE) {
    print_r($arr);
} else {
    echo "JSON字符串格式错误:" . json_last_error_msg();
}
?>
Copy after login

The output result is: JSON string format error: Syntax error

Summary

In PHP, we can use The built-in function json_decode() converts a JSON-formatted string into an array. If an error occurs when parsing a JSON string, we can use the try-catch statement to catch the exception or use the json_last_error() function to obtain the error information and process it according to different error codes. This article introduces two methods of handling errors, which can be chosen according to the actual situation.

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

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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to Implement message queues (RabbitMQ, Redis) in PHP? How to Implement message queues (RabbitMQ, Redis) in PHP? Mar 10, 2025 pm 06:15 PM

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

What Are the Latest PHP Coding Standards and Best Practices? What Are the Latest PHP Coding Standards and Best Practices? Mar 10, 2025 pm 06:16 PM

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

How Do I Work with PHP Extensions and PECL? How Do I Work with PHP Extensions and PECL? Mar 10, 2025 pm 06:12 PM

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

How to Use Reflection to Analyze and Manipulate PHP Code? How to Use Reflection to Analyze and Manipulate PHP Code? Mar 10, 2025 pm 06:12 PM

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

How Do I Stay Up-to-Date with the PHP Ecosystem and Community? How Do I Stay Up-to-Date with the PHP Ecosystem and Community? Mar 10, 2025 pm 06:16 PM

This article explores strategies for staying current in the PHP ecosystem. It emphasizes utilizing official channels, community forums, conferences, and open-source contributions. The author highlights best resources for learning new features and a

How to Use Asynchronous Tasks in PHP for Non-Blocking Operations? How to Use Asynchronous Tasks in PHP for Non-Blocking Operations? Mar 10, 2025 pm 04:21 PM

This article explores asynchronous task execution in PHP to enhance web application responsiveness. It details methods like message queues, asynchronous frameworks (ReactPHP, Swoole), and background processes, emphasizing best practices for efficien

How to Use Memory Optimization Techniques in PHP? How to Use Memory Optimization Techniques in PHP? Mar 10, 2025 pm 04:23 PM

This article addresses PHP memory optimization. It details techniques like using appropriate data structures, avoiding unnecessary object creation, and employing efficient algorithms. Common memory leak sources (e.g., unclosed connections, global v

See all articles