Home >Backend Development >PHP Tutorial >How can I sort a multidimensional array in PHP using multiple columns with `array_multisort()`?

How can I sort a multidimensional array in PHP using multiple columns with `array_multisort()`?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-16 14:23:15111browse

How can I sort a multidimensional array in PHP using multiple columns with `array_multisort()`?

Sorting Multidimensional Arrays by Multiple Columns

Sorting multidimensional arrays using multiple criteria can be a complex task, but it's crucial for organizing and retrieving data efficiently. This question explores how to sort a multidimensional array based on multiple columns using array_multisort().

Understanding array_multisort()

array_multisort() is a built-in PHP function that can sort arrays with multiple criteria. It takes an arbitrary number of arrays as input, representing the columns to sort by. The corresponding elements from each input array are compared for sorting.

Implementation

  1. Identify Sort Keys: Determine the columns you want to sort by. In this case, you have 'state,' 'event_type,' and 'date_start.'
  2. Get Column Data: Create an array ($sort) to store the values for the specified sort keys. Loop through the original array and extract the data for each key.
  3. Sort Columns: Call array_multisort() with the $sort array. Specify the desired sorting order for each column (e.g., SORT_DESC for 'state').
  4. Update Original Array: After sorting, array_multisort() modifies the original array ($mylist).

Example Code

$sort = array();
foreach($mylist as $k=>$v) {
    $sort['state'][$k] = $v['state'];
    $sort['event_type'][$k] = $v['event_type'];
    $sort['date_start'][$k] = $v['date_start'];
}

array_multisort($sort['state'], SORT_ASC,
                $sort['event_type'], SORT_DESC,
                $sort['date_start'], SORT_ASC,
                $mylist);

Result:

The $mylist array will be sorted in ascending order by 'state,' descending order by 'event_type,' and ascending order by 'date_start.'

The above is the detailed content of How can I sort a multidimensional array in PHP using multiple columns with `array_multisort()`?. 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