Home > Backend Development > PHP Tutorial > How to Efficiently Sort a Multidimensional PHP Array by Column, Including Dates and Custom Criteria?

How to Efficiently Sort a Multidimensional PHP Array by Column, Including Dates and Custom Criteria?

Susan Sarandon
Release: 2024-12-20 16:34:09
Original
846 people have browsed it

How to Efficiently Sort a Multidimensional PHP Array by Column, Including Dates and Custom Criteria?

Sorting a Multidimensional Array in PHP: A Flexible Approach

The Query

How do you efficiently arrange a multidimensional array based on a specified column, particularly when the data includes dates and you desire customized sorting criteria?

The Answer

Introducing an Enhanced Solution for PHP 5.3

This solution offers several advantages:

  • Reusable: Define the sort column as a variable.
  • Flexible: Handle multiple sort columns and secondary tiebreakers.
  • Reversible: Sort in either ascending or descending order for each column.
  • Extensible: Utilize custom projections for complex or non-comparable data.
  • Associative: Use usort or uasort for compatibility with associative arrays.

The Code

function make_comparer() {
    // Normalize criteria
    $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) {
            // Comparison details
            list($column, $sortOrder, $projection) = $criterion;
            $sortOrder = $sortOrder === SORT_DESC ? -1 : 1;

            // Project and compare values
            $lhs = $projection ? call_user_func($projection, $first[$column]) : $first[$column];
            $rhs = $projection ? call_user_func($projection, $second[$column]) : $second[$column];

            // Determine the comparison result
            if ($lhs < $rhs) {
                return -1 * $sortOrder;
            } elseif ($lhs > $rhs) {
                return 1 * $sortOrder;
            }
        }

        // Tiebreakers exhausted
        return 0;
    };
}
Copy after login

Usage

Consider the sample data:

$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'),
);
Copy after login

Basic Sorting:

  • Sort by the "name" column: usort($data, make_comparer('name'));

Sorting with Multiple Columns:

  • Sort by the "number" column and then by the zero-indexed column: usort($data, make_comparer('number', 0));

Advanced Features:

  • Reverse Sorting: Sort by the "name" column descending: usort($data, make_comparer(['name', SORT_DESC]));
  • Custom Projections: Project birthday dates to timestamps for sorting: usort($data, make_comparer(['birthday', SORT_ASC, 'date_create']));

Complex Use Case:

  • Sort by the "number" column descending, followed by the projected "birthday" column ascending:

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

The above is the detailed content of How to Efficiently Sort a Multidimensional PHP Array by Column, Including Dates and Custom Criteria?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template