Sorting Multi-Dimensional Arrays in PHP »

Every time I need to sort a multi-dimensional array in PHP, I have to remind myself how to do it. It’s not quite as quick and easy to look up as most things, so I’m going to blog a quick example. I’ve always felt like there must be a better way to do this, so please let me know if there is, and I’ll update this post accordingly.

Here’s a simple array of users:

$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:

$usernames = array();

foreach ($users as $user) {
    $usernames[] = $user['username'];
}

I then use array_multisort():

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:

$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.

Posted on: Friday, July 1, 2011 05:02 AM | under: , ,