数组的php显示顺序(排序)示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数组的php显示顺序(排序)示例相关的知识,希望对你有一定的参考价值。

  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. }

以上是关于数组的php显示顺序(排序)示例的主要内容,如果未能解决你的问题,请参考以下文章

PHP二维数组按照指定的顺序排序

两个 php 数组 - 用另一个数组的值顺序对一个数组进行排序

php 按字母顺序排序数组然后按数字排序

按自定义顺序对数组的php数组进行排序

按照顺序排序

php按照指定顺序的排序