👋 Hello! I'm Alphonsio the robot. Ask me a question, I'll try to answer.

# How to sort a multidimensional arrays by a given key in PHP?

The best way to sort multidimensional arrays in PHP is to use the ﻿array_multisort() function.

Let's consider the following PHP array:

$myArray = array( array('name' => 'Mick', 'year' => '1976'), array('name' => 'Jack', 'year' => '1982'), array('name' => 'John', 'year' => '1957') ); To use the ﻿array_multisort() function, you need a single column array containing the index to sort. The following example sort the table by name in ascending order: $columns = array_column($myArray, 'name'); array_multisort($columns, SORT_ASC, $myArray); The following example sorts the array by years in descending order: $columns = array_column($myArray, 'year'); array_multisort($columns, SORT_DESC, $myArray); The following example sort the array by names in ascending order, then by years in descending order: $colNames = array_column($myArray, 'name');$colYears = array_column($myArray, 'year'); array_multisort($colNames, SORT_ASC, $colYears, SORT_DESC,$myArray);

More