/ Published in: PHP
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/* This is a very basic example of how to change the sort order of an array. This information would normally be sent back to a database table. */ $arr[27]['id'] = 27; $arr[27]['order'] = 1; $arr[27]['name'] = 'about'; $arr[38]['id'] = 38; $arr[38]['order'] = 2; $arr[38]['name'] = 'contact'; $arr[52]['id'] = 52; $arr[52]['order'] = 3; $arr[52]['name'] = 'FAQ'; $arr[44]['id'] = 44; $arr[44]['order'] = 4; $arr[44]['name'] = 'Services'; $arr[45]['id'] = 45; $arr[45]['order'] = 5; $arr[45]['name'] = 'Sitemap'; echo 'original '.'<br />'; foreach($arr as $item) { echo 'Order: '.$item['order'].' '.$item['name'].'<br />'; } $id = 44; $int_new_order = 1; $int_current_order = 4; if( $int_new_order > $arr[$id]['order'] ) { //echo 'move higher in number'; foreach($arr as $k=>$v) { if( $v['order'] > $int_current_order AND $v['order'] <= $int_new_order) { $arr[$k]['order'] = $v['order']-1; } } } else { //echo 'move lower in number'; foreach($arr as $k=>$v) { if( $v['order'] < $int_current_order AND $v['order'] >= $int_new_order) { $arr[$k]['order'] = $v['order']+1; } } } $arr[$id]['order'] = $int_new_order; echo '<br />'; echo 'final '.'<br />'; foreach($arr as $item) { echo 'Order: '.$item['order'].' '.$item['name'].'<br />'; }