Home  >  Article  >  Backend Development  >  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

PHPz
PHPzOriginal
2023-04-19 10:08:13337browse

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;
}

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(
    '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