59

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?

gam6itko
  • 15,128
  • 2
  • 19
  • 18
Michael Ecklund
  • 1,206
  • 2
  • 17
  • 30
  • 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. – halfer Apr 03 '12 at 19:39

1 Answers1

147

Use usort which is built explicitly for this purpose.

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

usort($array, "cmp");
user229044
  • 232,980
  • 40
  • 330
  • 338
  • 23
    You can multiply by -1 to reverse the sort as well, just an FYI to anyone who may need to do so. – Kyle Crossman Feb 13 '14 at 21:30
  • 50
    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"]); }); ` – Gabi Lee Oct 11 '16 at 08:35
  • 8
    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. – stealthysnacks Feb 14 '17 at 22:26
  • 2
    @KyleCrossman we can also pass the arguments in a different order to obtain a reverse sort. – Talha Imam Jan 15 '21 at 12:10
  • 5
    For php7.4 and up `usort($array, fn($a, $b) => $a['title'] <=> $b['title']);` – pmiguelpinto90 Aug 05 '21 at 14:14