Home >Backend Development >PHP Tutorial >How to Sort Multidimensional Arrays in PHP Using a Flexible and Reusable Function?

How to Sort Multidimensional Arrays in PHP Using a Flexible and Reusable Function?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-01 07:29:09483browse

How to Sort Multidimensional Arrays in PHP Using a Flexible and Reusable Function?

How to Sort a Multidimensional Array in PHP

Introducing a Generalized Solution for PHP 5.3

Implementation:

function make_comparer() {
    // Normalize criteria up front
    $criteria = func_get_args();
    foreach ($criteria as $index => $criterion) {
        $criteria[$index] = is_array($criterion)
            ? array_pad($criterion, 3, null)
            : array($criterion, SORT_ASC, null);
    }

    return function($first, $second) use (&$criteria) {
        foreach ($criteria as $criterion) {
            list($column, $sortOrder, $projection) = $criterion;
            $sortOrder = $sortOrder === SORT_DESC ? -1 : 1;

            if ($projection) {
                $lhs = call_user_func($projection, $first[$column]);
                $rhs = call_user_func($projection, $second[$column]);
            } else {
                $lhs = $first[$column];
                $rhs = $second[$column];
            }

            if ($lhs < $rhs) {
                return -1 * $sortOrder;
            } elseif ($lhs > $rhs) {
                return 1 * $sortOrder;
            }
        }

        return 0; // tiebreakers exhausted
    };
}

Advanced Features:

(1) Multiple Sort Columns:

usort($data, make_comparer('number', 'name'));

(2) Reverse Sort:

usort($data, make_comparer(['name', SORT_DESC]));

(3) Custom Projections:

usort($data, make_comparer(['birthday', SORT_ASC, 'date_create']));

(4) Combining Features:

usort($data, make_comparer(
    ['number', SORT_DESC],
    ['birthday', SORT_ASC, 'date_create']
));

Benefits:

  • Reusable
  • Flexible
  • Reversible
  • Extensible
  • Associative

The above is the detailed content of How to Sort Multidimensional Arrays in PHP Using a Flexible and Reusable Function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn