PHP Compare Multi-dimensional Array Function


/ Published in: PHP
Save to your folder(s)

For more information, see php.net, under usort

It works with dates

Replace 0 for the array's key you want to sort. For example, if you have a start_date array key you would like to compare, then you would replace 0 for start_date.

If you want to do a reverse sort, just switch the -1 and 1.


Copy this code and paste it in your HTML
  1. function compare ($a, $b) {
  2. //return strcmp($a["fruit"], $b["fruit"]);
  3. // in the case of the above array
  4. // note we are comparing the first element of each array
  5. if ( $a[0] < $b[0] ) {
  6. return -1;
  7. }
  8. if ( $a[0] > $b[0] ) {
  9. return 1;
  10. }
  11. // they are equal
  12. return 0;
  13. }
  14.  
  15. usort($events, 'compare');

URL: www.coderemix.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.