This article to share is about the PHP custom recursive function How to implement the function of the array to JSON, the content is very good, the need for friends can refer to, hope can help everyone.
In this paper, we describe the function of PHP custom recursive function to implement array to JSON. Share to everyone for your reference, as follows:
Problem:
Since one of the most recent projects is to provide interfaces to other companies and feed them GBK encoded JSON data, one problem is that the json_encode
cryptographic functions in PHP only support utf-8 encoding, which is more embarrassing. Our data is GBK encoded, the receiver requested the data format is also GBK encoding, the first thought is to convert the data to UTF-8 encoding and then use the json_encode
function, the result is that our Chinese content is garbled, so, finally, the use of manual data encryption method.
Realize:
To achieve this function, the most important thing is to observe the characteristics of the JSON data, the beginning of the LZ summary is not in place resulting in the function can not be fully implemented json_encode
, followed by reference to the online data, the realization of this function (is a recursive function):
function Newarraytojson ($array) { if (!is_array ($array)) { return '; } $func = __function__; The key judgment is not an associative array, which determines whether JSON encryption key is required and uses [] $associative = (Array_keys ($array)!== range (0, COUNT ($array)-1))? True:fa LSE; if ($associative &&!empty ($array)) { $construct = array (); foreach ($array as $key = = $value) { $key = ' "'. $key. '"; if (Is_array ($value)) { $value = $func ($value); } ElseIf (!is_numeric ($value)) { $value = ' "'. $value. '"; } $construct [] = "$key: $value"; } $result = "{". Implode (",", $construct). "}"; else { $construct = array (); foreach ($array as $value) { if (Is_array ($value)) { $value = $func ($value); } else if (!is_numeric ($value)) { $value = ' "'. $value. '" '; } $construct [] = $value; } $result = "[". Implode (",", $construct). "]"; } return $result;}
Test: $arr =array (' 1 ' = ' www.jb51.net ', ' 2 ' = ' = ' www.baidu.com ', ' 3 ' = ' www.sina.com.cn ', ' 4 ' = ' Home of the script '); echo Newarraytojson ($arr);/* Run Result: {"1": "Www.jb51.net", "2": "Www.baidu.com", "3": "Www.sina.com.cn", "4": "Home of the script"}*/