Example
The code is as follows: |
Copy code |
Function encodeConvert ($ str, $ fromCode, $ toCode) { If (strtoupper ($ toCode) = strtoupper ($ fromCode) return $ str; If (is_string ($ str )){ If (function_exists ('MB _ convert_encoding ')){ Return mb_convert_encoding ($ str, $ toCode, $ fromCode ); } Else { Return iconv ($ fromCode, $ toCode, $ str ); } } Elseif (is_array ($ str )){ Foreach ($ str as $ k => $ v ){ $ Str [$ k] = encodeConvert ($ v, $ fromCode, $ toCode ); } Return $ str; } Return $ str; } |
Example
The code is as follows: |
Copy code |
/*************************************** *********************** * * Convert an array to a JSON string (compatible with Chinese characters) * @ Param array $ array the array to be converted * @ Return string the converted json string * @ Access public * **************************************** *********************/ Function JSON ($ array ){ ArrayRecursive ($ array, 'urlencode', true ); $ Json = json_encode ($ array ); Return urldecode ($ json ); } /*************************************** *********************** * * Use a specific function to process all elements in the array * @ Param string & $ array the string to be processed * @ Param string $ function the function to be executed * @ Return boolean $ apply_to_keys_also whether it is also applied to the key * @ Access public * **************************************** *********************/ Function arrayRecursive (& $ array, $ function, $ apply_to_keys_also = false ){ Static $ recursive_counter = 0; If (++ $ recursive_counter> 1000 ){ Die ('possible deep recursion attack '); } Foreach ($ array as $ key => $ value ){ If (is_array ($ value )){ ArrayRecursive ($ array [$ key], $ function, $ apply_to_keys_also ); } Else { $ Array [$ key] = $ function ($ value ); } If ($ apply_to_keys_also & is_string ($ key )){ $ New_key = $ function ($ key ); If ($ new_key! = $ Key ){ $ Array [$ new_key] = $ array [$ key]; Unset ($ array [$ key]); } } } $ Recursive_counter --; } |
Test example
The code is as follows: |
Copy code |
$ Arr = array ( Array ( 'Catid' => '4 ', 'Catname' => 'yunqi community net ', 'Meta _ title' => 'yunqi community network 2' ), Array ( 'Catid' => '55 ', 'Catname' => 'php ', 'Meta _ title' => 'http: // www.111cn.net ', ) ); Echo JSON ($ arr ); Echo json_encode (encodeConvert ($ arr, 'gb2312', 'utf-8 '));/**/
|
The output result is as follows:
[{"Catid": "4", "catname": "Yunqi Community Network", "meta_title": "Yunqi Community Network 2" },{ "catid": "55 ", "catname": "php Tutorial", "meta_title": "http://www.111cn.net"}]
[{"Catid": "4", "catname": "\ u4e00 \ u805a \ u6559 \ u7a0b \ u7f51", "meta_title ": "\ u4e00 \ u805a \ u6559 \ u7a0b \ u7f512" },{ "catid": "55", "catname": "php \ u6559 \ u7a0b", "meta_title ": "http: \ // www.111cn.net"}]