PHP sorted in the order specified

Source: Internet
Author: User

Today, when you encounter a requirement, you need to sort an array in a specified order and finally find a workaround:

$sort _rule = [5,7,3,1,8,2];

      $arr = [1,2,3,5,7,8];  

Requirements, sort the array $arr in the order specified by the $sort _rule

Workaround 1

$a = Array_intersect ($sort _rule,$arr);

$b = Array_diff ($arr,$sort _rule);

$re = Array_merge ($a, $b);

  The purpose of the Array_intersect function is to get the intersection of two arrays based on the first array, as in the example above

   array_intersect ( $sort _rule,

    first according to $sort _ The first element in rule takes the same element from the

Therefore, the order of the last obtained array of intersections is identical to the order of the $sort _sule array, and the requirement to sort in the order specified by Sort_rule is achieved.

Workaround 2

Usort ($arr, function ($a, $b) use ($rule) {

return (Array_search ($a, $rule) < Array_search ($b, $rule))?-1: 1;

The collation is passed into the closure function with use, and if the position of the element $a in the $rule is less than the position of the $b in the $rule, then 1 is returned, and vice versa returns 1,// The Usort function adjusts the position of the $a and $b according to the return value of the closure function });

PHP sorted in the order specified

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.