Using asort in PHP to solve the problem of Chinese sorting failure, _PHP tutorial

WBOY
Release: 2016-07-13 10:20:40
Original
808 people have browsed it

Use asort in PHP to solve the problem of Chinese sorting failure,

There is a very convenient method for reordering arrays in PHP - asort. You can see here for how to use asort. But when asort sorts an array containing Chinese keys, sometimes it is not in alphabetical order. This is mainly an encoding problem. If the encoding is UTF-8, it will not be sorted in alphabetical order. The solution is to convert to GBK encoding first, and then convert back to UTF-8 after sorting.

Example: There is an array $pass with a structure similar to

Array
(
 [0] => stdClass Object
  (
   [username] => 张三
   [password] => DQ9uqQW2+UudOsZpQMnyvGG9L+RHZB6LRzBVDvAEL9uOBNf2zTWUnykhZFjhbzCH+LrSslRx9eSqU/n3gSLSUA==
  )

 [1] => stdClass Object
  (
   [username] => 李四
   [password] => 2P/3j50ibk1BYmjHL+7/tt0d6LuOQMN9m8klXJCZbcajQtH5749jFTtH17WxiBZ9p425b4KIV/Xdv/7Bu4pJAQ==
  )

 [2] => stdClass Object
  (
   [username] => 王五
   [password] => caq8lq0l6uxJPRx+sCBsBFUojSF+ox98gwO6c/AquXQ/y/aj/l/ziEGsXRSV+olcK7iKOJJ4IZZvX8DMPWZRRA==
  )

 [3] => stdClass Object
  (
   [username] => 赵六
   [password] => taXp4jX0vO3VoFLyANfGrSjzy76WQQHMnzYAN9CyI20uKxLFMScXrFR3P525eImy0pG5zk8btBJoS/RyMxzJGQ==
  )

)

Copy after login

Using the following code, this array will be sorted according to the pinyin of username.

foreach ($pass as $key) {
 $key->username = iconv('UTF-8', 'GBK', $key->username);
}
asort( $pass );
foreach ($pass as $key) {
 $key->username = iconv('GBK', 'UTF-8', $key->username);
}
Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/865619.htmlTechArticleUsing asort in PHP to solve the problem of Chinese sorting failure, there is a very convenient way to reorder arrays in PHP Method - asort, you can see here for how to use asort. But...
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!