php two dimensional array sorting method of array_multisort usort

  • 2020-12-09 00:46:20
  • OfStack

For example, look at the following array:


$users = array(
    array('name' => 'tom', 'age' => 20)
    , array('name' => 'anny', 'age' => 18)
    , array('name' => 'jack', 'age' => 22)
);

I want to sort age from small to large. The author collates two methods to come out, share to everybody.

1. Use array_multisort

Using this method, which is a bit trickier, you extract age and store it in a 1-dimensional array, then sort it in ascending age order. The specific code is as follows:


$ages = array();
foreach ($users as $user) {
    $ages[] = $user['age'];
}
array_multisort($ages, SORT_ASC, $users);

Once executed, $users is a sorted array that you can print out to see. If the sorting method needs to be sorted in ascending order of age first and then in ascending order of name, the method is the same as above, that is, one more name array is extracted, and the final sorting method is called as follows:


array_multisort($ages, SORT_ASC, $names, SORT_ASC, $users);

2. usort

The biggest benefit of using this method is that you can customize some of the more complex sorting methods. For example, in descending order of length by name:


usort($users, function($a, $b) {
            $al = strlen($a['name']);
            $bl = strlen($b['name']);
            if ($al == $bl)
                return 0;
            return ($al > $bl) ? -1 : 1;
        });

Anonymous functions are used here and can be extracted separately if necessary. Where $a, $b can be understood as the element under the $users array. You can directly index the name value, calculate the length, and then compare the length.

I prefer the second method because there are fewer steps to extract the sorted content into a 1-dimensional array, and the sorting method is more flexible.


Related articles: