News Archive
PhpRiot Newsletter
Your Email Address:

More information

Sorting Multi-Dimensional Arrays in PHP

Note: This article was originally published at Planet PHP on 19 April 7420.
Planet 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:

A $users = array(); A $users[] = array('username' = 'shiflett', 'name' = 'Chris Shiflett'); $users[] = array('username' = 'dotjay', 'name' = 'Jon Gibbins'); $users[] = array('username' = 'a', 'name' = 'Andrei Zmievski'); A ?

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) A [1] = Array ([username] = dotjay [name] = Jon Gibbins) A [2] = Array ([username] = a [name] = Andrei Zmievski) A)

If I want to sort by username, I first create a separate array of usernames:

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

I then use array_multisort():

A array_multisort($usernames, SORT_ASC, $users); A ?

Here's the output of print_r($users) after sorting by username:

Array ([0] = Array ([username] = a [name] = Andrei Zmievski) A [1] = Array ([username] = dotjay [name] = Jon Gibbins) A [2] = Array ([username] = shiflett [name] = Chris Shiflett) A)

To s

Truncated by Planet PHP, read more at the original (another 2179 bytes)