Imagine you have Nested Sets tree, and you must to order it (by moving nodes) by some value (may be date, or some number value).

  1. $a = array();
  2.  
  3. for ($i = 0; $i < 15; $i++) {
  4. $a[rand(1, 1000)] = rand(1, 50);
  5. }
  6.  
  7. print_r($a);
  8.  
  9. asort($a);
  10. $c = array_keys($a);
  11.  
  12. print_r($a);
  13.  
  14. $q = array();
  15.  
  16. foreach ($a as $key => $value) {
  17. $aKey = array_search($key, $c, true);
  18. if (isset($c[$aKey + 1])) {
  19. $bKey = $c[$aKey + 1];
  20. array_unshift($q, array($value, $key, $bKey));
  21. }
  22. }
  23.  
  24. // proof-o-concept: how array can be created
  25. $r = array($key => $value);
  26.  
  27. foreach ($q as $data) {
  28. echo vsprintf("Moved %s from index %d before %dn", $data);
  29. $r = array_replace(array($data[1] => $data[0]), $r);
  30. }
  31.  
  32. print_r($r);
  33.  
  34.  
  35.  
  36.