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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks 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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24