sample php display order (sorting) for an array


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



Copy this code and paste it in your HTML
  1. /*
  2. This is a very basic example of how to change the sort order of an array.
  3. This information would normally be sent back to a database table.
  4. */
  5.  
  6. $arr[27]['id'] = 27;
  7. $arr[27]['order'] = 1;
  8. $arr[27]['name'] = 'about';
  9.  
  10.  
  11. $arr[38]['id'] = 38;
  12. $arr[38]['order'] = 2;
  13. $arr[38]['name'] = 'contact';
  14.  
  15.  
  16. $arr[52]['id'] = 52;
  17. $arr[52]['order'] = 3;
  18. $arr[52]['name'] = 'FAQ';
  19.  
  20.  
  21. $arr[44]['id'] = 44;
  22. $arr[44]['order'] = 4;
  23. $arr[44]['name'] = 'Services';
  24.  
  25. $arr[45]['id'] = 45;
  26. $arr[45]['order'] = 5;
  27. $arr[45]['name'] = 'Sitemap';
  28.  
  29.  
  30. echo 'original '.'<br />';
  31. foreach($arr as $item)
  32. {
  33. echo 'Order: '.$item['order'].' '.$item['name'].'<br />';
  34. }
  35.  
  36.  
  37.  
  38. $id = 44;
  39. $int_new_order = 1;
  40. $int_current_order = 4;
  41.  
  42. if( $int_new_order > $arr[$id]['order'] )
  43. {
  44. //echo 'move higher in number';
  45. foreach($arr as $k=>$v)
  46. {
  47.  
  48. if( $v['order'] > $int_current_order AND $v['order'] <= $int_new_order)
  49. {
  50. $arr[$k]['order'] = $v['order']-1;
  51. }
  52.  
  53. }
  54. }
  55. else
  56. {
  57. //echo 'move lower in number';
  58. foreach($arr as $k=>$v)
  59. {
  60.  
  61. if( $v['order'] < $int_current_order AND $v['order'] >= $int_new_order)
  62. {
  63. $arr[$k]['order'] = $v['order']+1;
  64. }
  65.  
  66. }
  67.  
  68. }
  69.  
  70. $arr[$id]['order'] = $int_new_order;
  71.  
  72. echo '<br />';
  73.  
  74. echo 'final '.'<br />';
  75. foreach($arr as $item)
  76. {
  77. echo 'Order: '.$item['order'].' '.$item['name'].'<br />';
  78. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.