-1

I have an array that is created like this:

$i = 0;

$files = array();   

while ($file = mysql_fetch_array($query_files)) {
    $files[$i] = array();
    $files[$i] = $file;
    $i++;
}

And I need to be able to sort the $files array based on each $file['name'] aka $files[$i]['name'].

How do I do this? Thanks!

Kermit
  • 33,827
  • 13
  • 85
  • 121
stingray-11
  • 448
  • 2
  • 7
  • 25
  • you mean alphabetically? – superUntitled Mar 22 '13 at 19:12
  • 5
    Would it not be easier to do the ordering in SQL (`ORDER BY name`)? – Clive Mar 22 '13 at 19:12
  • You could sort the data from your SQL query with "ORDER BY ..." – Superlandero Mar 22 '13 at 19:13
  • 1
    [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained [and are officially deprecated](http://j.mp/XqV7Lp). See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. – Kermit Mar 22 '13 at 19:13
  • 2
    ^ It's been a while since i've seen this comment – Daryl Gill Mar 22 '13 at 19:14

2 Answers2

8

Add ORDER BY NAME to your query. Seriously. That's the fastest, memory safest and all around best way to do it. I'm not kidding. Further, you'd be telling the database to do something it is awesome at, whereas PHP is only OK at it. Finally, you have the option to index the name column of the DB while PHP offers no index.

If you absolutely must sort it yourself, then you need to use usort.

// this example is almost a clone of something in the docs.
function cmp($a, $b)
{
    return strcmp($a["name"], $b["name"]);
}
usort($files, "cmp");
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
0

Looks like a job for usort

usort($array, function ($a, $b) {
   if ($a['name'] == $b['name']) {
       return 0;
   }
   return $a['name'] < $b['name'] ? -1 : 1;
});
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405