search
HomeBackend DevelopmentPHP ProblemHow to write a method to convert an array to JSON in php

In PHP programming, array is an important data structure. JSON is also a popular data format and is widely used in various web applications. In PHP, we often need to convert arrays into JSON format for easy transmission and storage. PHP provides the json_encode() method to convert an array into a JSON string. However, sometimes we may need to write an array-to-JSON method ourselves to better control the output format and logic. The following is an example method implementation:

/**
 * 将数组转换成JSON字符串
 * @param array $data 待转换的数组
 * @param int $indent 缩进量
 * @param int $level 当前层级
 * @return string 转换后的JSON字符串
 */
function arrayToJson($data, $indent = 0, $level = 0)
{
    $result = "";
    $space = str_repeat(" ", $indent);
    $isAssoc = is_assoc($data);

    if ($isAssoc) {
        $result .= "{\n";
    } else {
        $result .= "[\n";
    }

    foreach ($data as $key => $value) {
        if ($isAssoc) {
            $result .= $space . json_encode($key) . ": ";
        }

        if (is_array($value)) {
            $result .= arrayToJson($value, $indent + 4, $level + 1);
        } else if (is_bool($value)) {
            $result .= json_encode($value ? "true" : "false");
        } else if (is_null($value)) {
            $result .= "null";
        } else if (is_numeric($value)) {
            $result .= json_encode($value);
        } else {
            $result .= json_encode($value, JSON_UNESCAPED_UNICODE);
        }

        if (next($data)) {
            $result .= ",";
        }

        $result .= "\n";
    }

    $result .= str_repeat(" ", $level * 4);

    if ($isAssoc) {
        $result .= "}";
    } else {
        $result .= "]";
    }

    return $result;
}

/**
 * 判断一个数组是否是关联数组
 * @param array $data 待判断的数组
 * @return bool
 */
function is_assoc($data)
{
    if (!is_array($data)) {
        return false;
    }

    $keys = array_keys($data);
    $len = count($keys);

    for ($i = 0; $i <p>This method accepts an array as a parameter, as well as an "indentation" parameter and a "current level" parameter, these two parameters are used to format the output. Among them, the is_assoc() method is used to determine whether an array is an associative array. If so, we need to output both the keys and values ​​of the array elements when outputting. As for the value type, we adopt different encoding methods: </p>
  • If it is a subarray, the arrayToJson() method is called recursively for further processing.
  • If it is a Boolean type, convert it to the string "true" or "false" for output.
  • If it is null, output "null" directly.
  • If it is a number, use the json_encode() function to encode and output it.
  • If it is other types, also use the json_encode() function, but pass a JSON_UNESCAPED_UNICODE option parameter to retain the original Unicode code of non-ASCII characters.

In addition, we need to output a comma at the end of each child to support serialization of multiple involved elements. Finally, we output the corresponding "end symbol" according to the type of the array and return the formatted JSON string.

Using the above code, we can convert a PHP array into a JSON string, as shown below:

$data = array(
    'name' => 'John',
    'age' => 28,
    'married' => true,
    'hobbies' => array('basketball', 'music', 'reading'),
    'address' => array(
        'city' => 'Beijing',
        'country' => 'China'
    ),
    'friends' => array(
        array('name' => 'Tom', 'age' => 27),
        array('name' => 'Jane', 'age' => 26)
    )
);

echo arrayToJson($data);

The result output is as follows:

{
    "name": "John",
    "age": 28,
    "married": true,
    "hobbies": [
        "basketball",
        "music",
        "reading"
    ],
    "address": {
        "city": "Beijing",
        "country": "China"
    },
    "friends": [
        {
            "name": "Tom",
            "age": 27
        },
        {
            "name": "Jane",
            "age": 26
        }
    ]
}

In actual development, we It may be necessary to output a JSON string according to specific format requirements. At this point, the custom array to JSON method becomes very valuable.

The above is the detailed content of How to write a method to convert an array to JSON in php. 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

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

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools