PHP Sort array by field?

Go To StackoverFlow.com

28

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?

2012-04-03 19:25
by Michael Ecklund
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 2012-04-03 19:39


84

Use usort which is built explicitly for this purpose.

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

usort($array, "cmp");
2012-04-03 19:28
by meagar
You can multiply by -1 to reverse the sort as well, just an FYI to anyone who may need to do so - Kyle Crossman 2014-02-13 21:30
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 2016-10-11 08:35
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 2017-02-14 22:26
Ads