Home >Backend Development >PHP Problem >How to transcode an array in php
The way PHP transcodes an array is to use the mb_convert_encoding function to convert the character encoding, such as [mb_convert_encoding($value, "UTF-8", "GB2312");], which means converting GB2312 encoding to UTF -8.
The operating environment of this article: windows10 system, php 7.3, thinkpad t480 computer.
Two specific codes for transcoding arrays are shared below for your reference!
Introduction to the functions used:
array_map() function applies the user-defined function to each value in the array, and returns the user-defined function with new Array of values.
Function syntax:
array_map(myfunction,array1,array2,array3...)
Parameters:
myfunction The name of the user-defined function, or null.
array1 Specifies the array.
array2 Specifies the array.
#array3 Specifies the array.
The mb_convert_encoding function is used to convert character encoding.
Description:
mb_convert_encoding ( array|string $string , string $to_encoding , array|string|null $from_encoding = null ) : array|string|false
Convert the character encoding of string type str from optional from_encoding to to_encoding. When the parameter string is an array, all its string values will be converted recursively.
Convert GB2312 encoding to UTF-8
The specific code is as follows:
//更改编码为utf8 protected function array2utf8($array){ $array = array_map(function($value){ if(is_array($value)){ return $this->array2utf8($value); } else{ return mb_convert_encoding($value, "UTF-8", "GB2312"); } } , $array); return $array; }
Convert UTF-8 encoding to GB2312
The specific code is as follows:
protected function array2gbk($array){ $array = array_map(function($value){ if(is_array($value)){ return $this->array2gbk($value); } else{ return mb_convert_encoding($value, "GB2312", "UTF-8"); } } , $array); return $array; }
Related video sharing: php video tutorial
The above is the detailed content of How to transcode an array in php. For more information, please follow other related articles on the PHP Chinese website!