Home Backend Development PHP Problem How to write a method to convert an array to JSON in php

How to write a method to convert an array to JSON in php

Apr 19, 2023 am 10:08 AM

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 < $len; $i++) {
        if ($keys[$i] !== $i) {
            return true;
        }
    }

    return false;
}
Copy after login

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:

  • 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(
    &#39;name&#39; => '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);
Copy after login

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
        }
    ]
}
Copy after login

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 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 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)

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.

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 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 Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

How do you retrieve data from a database using PHP? How do you retrieve data from a database using PHP? Mar 20, 2025 pm 04:57 PM

Article discusses retrieving data from databases using PHP, covering steps, security measures, optimization techniques, and common errors with solutions.Character count: 159

PHP CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

What is the purpose of mysqli_query() and mysqli_fetch_assoc()? What is the purpose of mysqli_query() and mysqli_fetch_assoc()? Mar 20, 2025 pm 04:55 PM

The article discusses the mysqli_query() and mysqli_fetch_assoc() functions in PHP for MySQL database interactions. It explains their roles, differences, and provides a practical example of their use. The main argument focuses on the benefits of usin

See all articles