How to use Asort in PHP to deal with the problem of Chinese sort failure _php skills

Source: Internet
Author: User

There are very handy ways to reorder arrays in PHP--asort, the use of Asort can be seen here. However, when sorting an array containing Chinese keys, asort is sometimes not in alphabetical order. This is mainly a coding problem, if the encoding for UTF-8, it will not be sorted alphabetically, the solution is first converted into GBK encoding, sorted out and then back to UTF-8.

Example: There is an array of $pass, similar in structure to

Array
(
 [0] => stdClass Object
  (
   [username] => John
   [password] => dq9uqqw2+ uudoszpqmnyvgg9l+rhzb6lrzbvdvael9uobnf2ztwunykhzfjhbzch+lrsslrx9esqu/n3gslsua==
  )

 [1] => StdClass Object
  (
   [username] => dick
   [password] => 2p/3j50ibk1bymjhl+7/ tt0d6luoqmn9m8klxjczbcajqth5749jftth17wxibz9p425b4kiv/xdv/7bu4pjaq==
  )

 [2] => stdClass Object
  (
   [username] => Harry
   [Password] => caq8lq0l6uxjprx+scbsbfuojsf+ox98gwo6c/aquxq/y/aj/l/ziegsxrsv+olck7ikojj4izzvx8dmpwzrra==
  )

 [3] => stdClass Object
  (
   [username] => Zhao Liu
   [Password] => taxp4jx0vo3voflyanfgrsjzy76wqqhmnzyan9cyi20ukxlfmscxrfr3p525eimy0pg5zk8btbjos/rymxzjgq==
  )

)

Using the following code, the array will be sorted according to the pinyin of the 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);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.