Sort bidimensional array by one of it keys


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

Simple function that sorts a bi-dimensional array by one of it keys.


Copy this code and paste it in your HTML
  1. /**
  2.  * sort_array_by_key()
  3.  *
  4.  * @param array $array
  5.  * @param string|int $key
  6.  * @return array
  7.  *
  8.  * @author Alejo
  9.  */
  10. function array_sort_by_key($array, $key)
  11. {
  12. $tmpArKeys = array();
  13. foreach ($array as $ar_item)
  14. {
  15. $tmpArKeys[] = $ar_item[$key];
  16. }
  17. asort($tmpArKeys);
  18.  
  19. $newAr = array();
  20. foreach ($tmpArKeys as $n_key => $n_val)
  21. {
  22. $newAr[] = $array[$n_key];
  23. }
  24. return $newAr;
  25. }
  26.  
  27.  
  28. /// Example
  29.  
  30. $people = array(
  31. 'Name' => 'John',
  32. 'Lastname' => 'Doe',
  33. 'E-mail' => '[email protected]'
  34. ),
  35. 'Name' => 'Harry',
  36. 'Lastname' => 'Potter',
  37. 'E-mail' => '[email protected]'
  38. ),
  39. 'Name' => 'Lady',
  40. 'Lastname' => 'Gaga',
  41. 'E-mail' => '[email protected]'
  42. )
  43.  
  44. );
  45.  
  46. $sorted_people = array_sort_by_key($people, 'Name');
  47. print_r($sorted_people);
  48.  
  49. /// Example output:
  50. /*
  51. Array
  52. (
  53.   [0] => Array
  54.   (
  55.   [Name] => Harry
  56.   [Lastname] => Potter
  57.   [E-mail] => [email protected]
  58.   )
  59.  
  60.   [1] => Array
  61.   (
  62.   [Name] => John
  63.   [Lastname] => Doe
  64.   [E-mail] => [email protected]
  65.   )
  66.  
  67.   [2] => Array
  68.   (
  69.   [Name] => Lady
  70.   [Lastname] => Gaga
  71.   [E-mail] => [email protected]
  72.   )
  73.  
  74. )
  75.  
  76. */

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.