Disposal of Chinese Sorting Failure Using asort in PHP

  • 2021-07-13 04:35:15
  • OfStack

PHP has a very convenient way to reorder arrays-asort, the use of asort can be seen here. However, when asort sorts arrays containing Chinese key, it sometimes does not follow alphabetical order. This is mainly a coding problem. If the coding is UTF-8, it will not be arranged in alphabetical order. The solution is to convert it to GBK coding first, and then return to UTF-8 after sorting.

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


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

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

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

 [3] => stdClass Object
  (
   [username] =>  Zhao 6
   [password] => taXp4jX0vO3VoFLyANfGrSjzy76WQQHMnzYAN9CyI20uKxLFMScXrFR3P525eImy0pG5zk8btBJoS/RyMxzJGQ==
  )

)

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);
}


Related articles: