We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

iTony on 08/24/08


Tagged

sort array


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

luman


Sort a bidimensional array


Published in: PHP 


  1. // rellenamos una array
  2. $array[] = array('nombre'=>'miquel','edad'=>22);
  3. $array[] = array('nombre'=>'carlos','edad'=>29);
  4. $array[] = array('nombre'=>'hermann','edad'=>24);
  5. $array[] = array('nombre'=>'jorge','edad'=>21);
  6. $array[] = array('nombre'=>'daniel','edad'=>25);
  7. // declaramos la función de ordenación
  8. function cmp($a, $b)
  9. {
  10. if ($a["edad"] == $b["edad"]) {
  11. return 0;
  12. }
  13. return ($a["edad"] <$b["edad"]) ? -1 : 1;
  14. }
  15. // ordenamos segun la función de ordenación
  16. usort($array, "cmp");
  17. echo '<pre>';
  18. print_r($array);
  19. echo '</pre>';

Report this snippet 

You need to login to post a comment.