How to transcode an array in php

王林
Release: 2023-03-10 13:56:02
Original
2334 people have browsed it

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.

How to transcode an array in php

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...)
Copy after login

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
Copy after login

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;
}
  
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template