Php two-dimensional array sorting, php two-dimensional array sorting

Source: Internet
Author: User

Php two-dimensional array sorting, php two-dimensional array sorting

// Create a $ arr two-dimensional array $ arr = array ('name' => 'E', 'age' => 5 ), array ('name' => 'B', 'age' => 2), array ('name' => 'A', 'age' => 1 ), array ('name' => 'C', 'age' => 3), array ('name' => 'D', 'age' => 4 ),);

 

 

Two functions: strnatcmp and strncmp

// Function echo strnatcmp ("ac", 'AB') that compares the two strings '). "<br/>"; // output 1 echo strncmp ("ac", 'AB', 1 ). "<br/>"; // output 0 because this function has a third parameter that limits only 1-bit comparison, that is, only

 

// Use usort to sort the values in the array using the User-Defined comparison function // sort the values in the array by key value name ($ arr, function ($, $ B) {return strnatcmp ($ a ['name'], $ B ['name']); // directly compare the name field of the Two-dimensional array for asc sorting }); dump ($ arr); // sort the length of the key value name usort ($ arr, function ($ a, $ B) {if (strlen ($ a ['name']) = strlen ($ B ['name']) return 0; return (strlen ($ a ['name'])> strlen ($ B ['name'])? 1:0 ;}); dump ($ arr );


Print function

        function dump($data)    {        echo "<pre>";        print_r($data);        echo "</pre>";    }

 

 

 

Sort sorts ArraysIt is applicable to one-dimensional index arrays without indexes.

Rsort sorts arrays in reverse orderConsistent with sort usage

Asort sorts ArraysAnd keep the index relationship to sort the values. It is generally applicable to one-dimensional arrays and maintains the index relationship.

Arsort sorts arrays in reverse order and maintains the index relationship.Consistent with asort usage

Ksort sorts arrays by key names

Krsort sorts arrays in reverse order by key name

 

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.