PHP Array grouping Sort instance code

Source: Internet
Author: User

There is the following PHP array, the contents of the array:

    1. $list = Array (
    2. Array (2,3,5),
    3. Array (2,5,24),
    4. Array (3,8,6),
    5. Array (3,2,10),
    6. Array (4,7,20),
    7. Array (4,1,15),
    8. Array (6,4,10),
    9. Array (7,9,20),
    10. );
Copy Code

For ease of expression, I called the 3 column numbers, the ABC three-column requirement: By default the column A is the primary, and if the column A is the same, the same element is sorted in reverse column C. Column B actually does not participate in the sort, but it is useful in practical use, so it is also written out. Method One:

    1. $a = $c = Array ();
    2. foreach ($list as $val) {
    3. $a [] = $val [0]; Column A
    4. $c [] = $val [2]; Column C
    5. }
    6. Install column A ascending, and then install column B descending, similar to Sql,orderby a asc,b desc
    7. Array_multisort ($a, SORT_ASC, $c, Sort_desc, $list);
    8. Print_r ($list);
Copy Code

Method Two:

    1. for ($j =0; $j
    2. For ($i =count ($list)-1; $i > $j; $i-) {
    3. if ($list [$i][0] = = $list [$i -1][0] && $list [$i][2] > $list [$i -1][2])
    4. List ($list [$i], $list [$i-1]) = Array ($list [$i-1], $list [$i]);
    5. }
    6. }
Copy Code
  • 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.