64

Possible Duplicate:
how to sort a multidemensional array by an inner key
How to sort an array of arrays in php?

How can I sort an array like: $array[$i]['title'];

Array structure might be like:

array[0] (
  'id' => 321,
  'title' => 'Some Title',
  'slug' => 'some-title',
  'author' => 'Some Author',
  'author_slug' => 'some-author'
);

array[1] (
  'id' => 123,
  'title' => 'Another Title',
  'slug' => 'another-title',
  'author' => 'Another Author',
  'author_slug' => 'another-author'
);

So data is displayed in ASC order based off the title field in the array?

1
  • Michael: Tim was just being helpful. Searching first is a bit of a prerequisite here, and we get a lot of questioners that don't appear to have searched/tried first. Commented Apr 3, 2012 at 19:39

1 Answer 1

160

Use usort which is built explicitly for this purpose.

function cmp($a, $b)
{
    return strcmp($a["title"], $b["title"]);
}

usort($array, "cmp");
Sign up to request clarification or add additional context in comments.

6 Comments

You can multiply by -1 to reverse the sort as well, just an FYI to anyone who may need to do so.
Starting PHP 5.3 you can use anonymous functions, which is helpful especially if you're inside a class in a namespace: usort($domain_array, function ($a, $b) { return strcmp($a["name"], $b["name"]); });
Just to add on a bit to @GabiLee, if you want the search field to be dynamic based on some variable you already have set, try this: usort($domain_array, function ($a, $b) use ($searchField) { return strcmp($a[$searchField], $b[$searchField]); }); This might be useful for example on a web page where the user can choose a field to sort by.
@KyleCrossman we can also pass the arguments in a different order to obtain a reverse sort.
For php7.4 and up usort($array, fn($a, $b) => $a['title'] <=> $b['title']);
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.