Troubleshooting of invalid Chinese sorting using asort in PHP

Source: Internet
Author: User
The asort () function sorts arrays and maintains the index relationship. It is mainly used to sort the arrays that are very important to the unit order. The second optional parameter contains an additional sorting identifier. TRUE is returned if the call succeeds,

The asort () function sorts arrays and maintains the index relationship. It is mainly used to sort the arrays that are very important to the unit order. The second optional parameter contains an additional sorting identifier. TRUE is returned if the call succeeds,

PHP has a very convenient method for re-sorting Arrays-asort. For more information about how to use asort, see here. However, when asort sorts arrays containing Chinese keys, it sometimes does not follow the alphabetic order. This is mainly the encoding problem, if the encoding is UTF-8, it will not sort in alphabetical order, the solution is to first convert to GBK encoding, sorting and then back to the UTF-8.

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

Array ([0] => stdClass Object ([username] => JOHN [password] => DQ9uqQW2 + udoszpqmnyvgg9l + example + LrSslRx9eSqU/nw.slsua =) [1] => stdClass Object ([username] => Li Si [password] => 2 P/3j50ibk1BYmjHL + 7/tests/Xdv/7Bu4pJAQ =) [2] => stdClass Object ([username] => Wang Wu [password] => caq8lq0l6uxJPRx + sCBsBFUojSF + ox98gwO6c/AquXQ/y/aj/l/ziegsxclr + Signature =) [3] => stdClass Object ([username] => Zhao Liu [password] => ghost/RyMxzJGQ = ))

The following code sorts the array by username in pinyin.

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.