code_junkie

Sorting an Array of Objects in PHP In a Specific Order

Nov 12th, 2011
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. Array
  2. (
  3. [0] => stdClass Object
  4. (
  5. [ID] => 1
  6. [user_login] => user1
  7. )
  8. [1] => stdClass Object
  9. (
  10. [ID] => 6
  11. [user_login] => user6
  12. )
  13. [2] => stdClass Object
  14. (
  15. [ID] => 8
  16. [user_login] => user8
  17. )
  18. )
  19.  
  20. Array
  21. (
  22. [0] => stdClass Object
  23. (
  24. [ID] => 8
  25. [user_login] => user8
  26. )
  27. [1] => stdClass Object
  28. (
  29. [ID] => 1
  30. [user_login] => user1
  31. )
  32. [2] => stdClass Object
  33. (
  34. [ID] => 6
  35. [user_login] => user6
  36. )
  37. )
  38.  
  39. function cmp($a, $b)
  40. {
  41. global $author_array;
  42.  
  43. $pos1=array_search ($a->ID, $author_array);
  44. $pos2=array_search ($b->ID, $author_array);
  45.  
  46. if ($pos1==$pos2)
  47. return 0;
  48. else
  49. return ($pos1 < $pos2 ? -1 : 1);
  50.  
  51. }
  52.  
  53.  
  54. usort($user_results, "cmp");
  55.  
  56. $hash = array();
  57. $result = array();
  58.  
  59. foreach ($user_results as $obj) {
  60. $hash[$obj->ID] = $obj;
  61. }
  62.  
  63. foreach ($author_array as $id) {
  64. $result[] = $hash[$id];
  65. }
  66.  
  67. $sort_array= array(11, 4, 16, 19, 23);
  68. $myobject = sort_categories($myobject)
  69.  
  70. function cmp($a, $b) {
  71. if ($a->sort_key == $b->sort_key) { return 0; }
  72. return ($a->sort_key < $b->sort_key) ? -1 : 1;
  73. }
  74. function sort_categories($obj) {
  75. global $sort_array;
  76.  
  77. foreach($obj as $cat) {
  78. $cat->sort_key = 999;
  79. for ($i=0;$i<count($sort_array);$i++) {
  80. if ($sort_array[$i] == $cat->term_id) $cat->sort_key = $i;
  81. }
  82. }
  83. usort($obj,'cmp');
  84. return $obj;
  85. }
Add Comment
Please, Sign In to add comment