Home >Backend Development >PHP Tutorial >How Can I Efficiently Sort Multidimensional Arrays in PHP?

How Can I Efficiently Sort Multidimensional Arrays in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-22 02:30:17755browse

How Can I Efficiently Sort Multidimensional Arrays in PHP?

Sorting Multidimensional Arrays in PHP: A Versatile Solution

This comprehensive guide addresses the task of sorting multidimensional arrays in PHP. It offers a reusable and highly customizable solution that empowers you with the ability to sort your data effortlessly.

The Solution: make_comparer() Function

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) {
            // Determine sort criteria
            list($column, $sortOrder, $projection) = $criterion;
            $sortOrder = $sortOrder === SORT_DESC ? -1 : 1;

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

            // Compare values; do not return if equal
            if ($lhs < $rhs) {
                return -1 * $sortOrder;
            } elseif ($lhs > $rhs) {
                return 1 * $sortOrder;
            }
        }

        return 0; // tiebreakers exhausted, so $first == $second
    };
}

How to Use

Basic Usage: Sorting by a Single Column

// Sort $data by the "name" column using uasort
$data = array(
    array('zz', 'name' => 'Jack', 'number' => 22, 'birthday' => '12/03/1980'),
    array('xx', 'name' => 'Adam', 'number' => 16, 'birthday' => '01/12/1979'),
    array('aa', 'name' => 'Paul', 'number' => 16, 'birthday' => '03/11/1987'),
    array('cc', 'name' => 'Helen', 'number' => 44, 'birthday' => '24/06/1967'),
);
uasort($data, make_comparer('name'));

Sorting by Multiple Columns:

// Sort $data by "number" and then by the zero-indexed column (ID)
uasort($data, make_comparer('number', 0));

Advanced Features

Reverse Sorting:

// Sort $data by "name" descending
uasort($data, make_comparer(['name', SORT_DESC]));

Custom Projections:

// Sort $data by "birthday" using date_create as a projection
uasort($data, make_comparer(['birthday', SORT_ASC, 'date_create']));

Combining Features:

// Sort $data by "number" descending and then by "birthday" ascending
uasort($data, make_comparer(
    ['number', SORT_DESC],
    ['birthday', SORT_ASC, 'date_create']
));

Conclusion

This solution provides a wide range of capabilities to sort multidimensional arrays in PHP. Its flexibility and ease of use make it a powerful tool for data manipulation in various scenarios.

The above is the detailed content of How Can I Efficiently Sort Multidimensional Arrays in PHP?. 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