How 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 < $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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

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.

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.

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.

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

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

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

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
