Home >Backend Development >PHP Tutorial >How can I sort multi-dimensional arrays in PHP by one or more keys?
When working with multi-dimensional arrays, it may be necessary to sort the array based on the value of a specific key. For instance, if you have an array containing a list of images, you might want to sort them by their date or size.
To sort an array by a single key, you can use the usort() function. This function takes two parameters: the array to be sorted and a sorting function. The sorting function must take two parameters, which represent the two elements to be compared.
For example, let's say we have the following array, and we want to sort it by the value of the "order" key:
Array ( [0] => Array ( [hashtag] => a7e87329b5eab8578f4f1098a152d6f4 [title] => Flower [order] => 3 ) [1] => Array ( [hashtag] => b24ce0cd392a5b0b8dedc66c25213594 [title] => Free [order] => 2 ) [2] => Array ( [hashtag] => e7d31fc0602fb2ede144d18cdffd816b [title] => Ready [order] => 1 ) )
To sort this array, we can use the following sorting function:
function sortByOrder($a, $b) { if ($a['order'] > $b['order']) { return 1; } elseif ($a['order'] < $b['order']) { return -1; } return 0; }
Then, we can pass this function to the usort() function:
usort($myArray, 'sortByOrder');
After sorting, the array will be ordered by the value of the "order" key:
Array ( [2] => Array ( [hashtag] => e7d31fc0602fb2ede144d18cdffd816b [title] => Ready [order] => 1 ) [1] => Array ( [hashtag] => b24ce0cd392a5b0b8dedc66c25213594 [title] => Free [order] => 2 ) [0] => Array ( [hashtag] => a7e87329b5eab8578f4f1098a152d6f4 [title] => Flower [order] => 3 ) )
To sort an array by multiple keys, you can use the following approach:
For example, let's say we have the following array, and we want to sort it by the value of the "order" key, and then by the value of the "title" key:
Array ( [0] => Array ( [hashtag] => a7e87329b5eab8578f4f1098a152d6f4 [title] => Flower [order] => 1 ) [1] => Array ( [hashtag] => b24ce0cd392a5b0b8dedc66c25213594 [title] => Free [order] => 2 ) [2] => Array ( [hashtag] => e7d31fc0602fb2ede144d18cdffd816b [title] => Free [order] => 2 ) [3] => Array ( [hashtag] => c1ede105cf8a54bbfb9f06542a9971bb [title] => Ready [order] => 3 ) )
To sort this array, we can use the following sorting function:
The above is the detailed content of How can I sort multi-dimensional arrays in PHP by one or more keys?. For more information, please follow other related articles on the PHP Chinese website!