Home Backend Development PHP Problem Convert php json data to array

Convert php json data to array

May 23, 2023 am 11:14 AM

In PHP, sometimes we need to convert JSON data into array format for processing. At this time, we can use the json_decode() function to convert JSON data into a PHP array. This article will introduce how to use the json_decode() function to convert JSON data into an array and answer some common questions.

JSON is a lightweight data exchange format that is widely used to transmit data due to its advantages of being simple to understand, easy to use, and easy to extend. PHP is a weakly typed programming language that is efficient, fast, easy to learn and use. Since JSON format is natively supported in PHP, it is very convenient to use PHP to process JSON data during development.

Use json_decode() function to convert JSON data into an array

The following is a sample code to convert a JSON data into an array:

$json = '{"name":"Tom","age":"20","sex":"male"}';

$arr = json_decode($json, true);

var_dump($arr);
Copy after login

Output result:

array(3) {
  ["name"]=>
  string(3) "Tom"
  ["age"]=>
  string(2) "20"
  ["sex"]=>
  string(4) "male"
}
Copy after login

As you can see, the json_decode() function converts JSON data into a PHP array. The second parameter of this function can be set to true or false, which returns an associative array when set to true, or an object when set to false or unset.

The following is a sample code to return an object:

$json = '{"name":"Tom","age":"20","sex":"male"}';

$obj = json_decode($json);

var_dump($obj);
Copy after login

Output result:

object(stdClass)#1 (3) {
  ["name"]=>
  string(3) "Tom"
  ["age"]=>
  string(2) "20"
  ["sex"]=>
  string(4) "male"
}
Copy after login

When parsing a JSON string, if it is found that the character encoding is not UTF-8, it needs to be converted Into UTF-8 encoding:

$json = '{"name":"Tom","age":"20","sex":"male"}';

$json = mb_convert_encoding($json, 'UTF-8', 'auto'); // 将编码转换为 UTF-8

$arr = json_decode($json, true);

var_dump($arr);
Copy after login

FAQ

1. How to deal with JSON parsing errors?

During the process of processing JSON data, parsing errors may occur due to problems with the JSON data format or encoding format. At this point, you can use the json_last_error() function to get the cause of the parsing error. This function returns a number representing the type of JSON parsing error. The following is the definition of the error type:

  • JSON_ERROR_NONE: No error, parsing successful.
  • JSON_ERROR_DEPTH: The JSON data is too complex and exceeds the set maximum depth.
  • JSON_ERROR_STATE_MISMATCH: The JSON data format is incorrect.
  • JSON_ERROR_CTRL_CHAR: There is an incorrect control character.
  • JSON_ERROR_SYNTAX: There is a syntax error in the JSON data.
  • JSON_ERROR_UTF8: The JSON data is not UTF-8 encoded.

Use the following code to obtain the cause of the parsing error:

$json = '{"name": "Tom""age": "20"}'; // 注意,这里有错误

$arr = json_decode($json, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    switch (json_last_error()) {
        case JSON_ERROR_DEPTH:
            echo 'JSON 数据过于复杂,超出了设置的最大深度';
            break;
        case JSON_ERROR_STATE_MISMATCH:
            echo 'JSON 数据格式不正确';
            break;
        case JSON_ERROR_CTRL_CHAR:
            echo 'JSON 数据中有不正确的控制字符';
            break;
        case JSON_ERROR_SYNTAX:
            echo 'JSON 数据存在语法错误';
            break;
        case JSON_ERROR_UTF8:
            echo 'JSON 数据不是 UTF-8 编码';
            break;
        default:
            echo '未知的 JSON 解析错误';
            break;
    }
}

var_dump($arr);
Copy after login

Output result:

JSON 数据存在语法错误
NULL
Copy after login

As shown above, the json_last_error() function can easily obtain the parsing error to quickly find the problem.

2. How to deal with the problem of non-standard JSON format?

In actual use, some JSON data may not be in the most standardized format, such as the use of a comma after the last attribute value. If you use the json_decode() function to parse this JSON data, NULL will be returned. At this point, we can use a third-party library for processing.

The following is a sample code that uses the json5 library to process JSON non-standard format:

// 首先,安装 json5 库
// composer require symfony/polyfill-mbstring
// composer require webonyx/json5

$json = '{"name": "Tom", "age": 20, }'; // 注意,这里有错误

use Json5Parser;

$parser = new Parser();
$arr = $parser->decode($json);

var_dump($arr);
Copy after login

Output result:

array(2) {
  ["name"]=>
  string(3) "Tom"
  ["age"]=>
  int(20)
}
Copy after login

As shown above, it can be easily processed using the json5 library Issues with JSON non-standard format.

3. How to deal with the problem of cross-domain access of JSON data?

The problem of cross-domain access of JSON data means that for security reasons, the browser prohibits the front-end from accessing resources in other domains across ajax requests. At this time, we need to make some settings.

The following is a sample code for using PHP to achieve cross-domain access:

header('Access-Control-Allow-Origin: *'); // 允许所有域名访问
header('Content-Type: application/json');

$json = '{"name": "Tom", "age": 20, "sex": "male"}';

echo $json;
Copy after login

As shown above, setting the Access-Control-Allow-Origin header in PHP allows other domain names to be cross-domain access.

Conclusion

So far, we have introduced how to use the json_decode() function to convert JSON data into an array, and how to solve some common problems encountered in processing JSON data. I hope this article can be helpful to everyone.

The above is the detailed content of Convert php json data to array. 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
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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)

What are the best practices for deduplication of PHP arrays What are the best practices for deduplication of PHP arrays Mar 03, 2025 pm 04:41 PM

This article explores efficient PHP array deduplication. It compares built-in functions like array_unique() with custom hashmap approaches, highlighting performance trade-offs based on array size and data type. The optimal method depends on profili

Can PHP array deduplication take advantage of key name uniqueness? Can PHP array deduplication take advantage of key name uniqueness? Mar 03, 2025 pm 04:51 PM

This article explores PHP array deduplication using key uniqueness. While not a direct duplicate removal method, leveraging key uniqueness allows for creating a new array with unique values by mapping values to keys, overwriting duplicates. This ap

Does PHP array deduplication need to be considered for performance losses? Does PHP array deduplication need to be considered for performance losses? Mar 03, 2025 pm 04:47 PM

This article analyzes PHP array deduplication, highlighting performance bottlenecks of naive approaches (O(n²)). It explores efficient alternatives using array_unique() with custom functions, SplObjectStorage, and HashSet implementations, achieving

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

What are the optimization techniques for deduplication of PHP arrays What are the optimization techniques for deduplication of PHP arrays Mar 03, 2025 pm 04:50 PM

This article explores optimizing PHP array deduplication for large datasets. It examines techniques like array_unique(), array_flip(), SplObjectStorage, and pre-sorting, comparing their efficiency. For massive datasets, it suggests chunking, datab

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

See all articles