Sorting Multi-Dimensional Arrays in PHP
30 Jun 2011Every time I need to sort a multi-dimensional array in PHP, I have to look it up. It's not quite as quick and easy to look up as most things, so I'm going to blog a quick example.
Here's a simple array of users:
<?php
$users = array();
$users[] = array('username' => 'shiflett', 'name' => 'Chris Shiflett');
$users[] = array('username' => 'dotjay', 'name' => 'Jon Gibbins');
$users[] = array('username' => 'a', 'name' => 'Andrei Zmievski');
?>
There are a few different ways to create this array. Here's the output of print_r($users)
, so you clearly understand the structure:
Array
(
[0] => Array
(
[username] => shiflett
[name] => Chris Shiflett
)
[1] => Array
(
[username] => dotjay
[name] => Jon Gibbins
)
[2] => Array
(
[username] => a
[name] => Andrei Zmievski
)
)
If I want to sort by username, I first create a separate array of usernames:
<?php
$usernames = array();
foreach ($users as $user) {
$usernames[] = $user['username'];
}
?>
I then use array_multisort()
:
<?php
array_multisort($usernames, SORT_ASC, $users);
?>
Here's the output of print_r($users)
after sorting by username:
Array
(
[0] => Array
(
[username] => a
[name] => Andrei Zmievski
)
[1] => Array
(
[username] => dotjay
[name] => Jon Gibbins
)
[2] => Array
(
[username] => shiflett
[name] => Chris Shiflett
)
)
To sort the array by name instead, I'd do something very similar:
<?php
$names = array();
foreach ($users as $user) {
$names[] = $user['name'];
}
array_multisort($names, SORT_ASC, $users);
?>
Here's the output of print_r($users)
after sorting by name:
Array
(
[0] => Array
(
[username] => a
[name] => Andrei Zmievski
)
[1] => Array
(
[username] => shiflett
[name] => Chris Shiflett
)
[2] => Array
(
[username] => dotjay
[name] => Jon Gibbins
)
)
There are many more uses of array_multisort()
, and there are many other useful sorting functions. Please feel free to share some of your favorites in the comments.
Update: If your array isn't too big, and especially if you find it easier to understand, you might prefer usort()
. Thanks to Franco Zeoli for this example:
<?php
// Sort the array by username.
usort($users, function ($a, $b) {
return strcmp($a['username'], $b['username']);
});
?>
If your array is large, or you're concerned about performance, make sure you read Jordi Boggiano's comment.