Home > Article > Backend Development > Using asort in PHP to solve the problem of Chinese sorting failure, _PHP tutorial
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== ) )
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); }