$a = array(); for ($i = 0; $i < 15; $i++) { $a[rand(1, 1000)] = rand(1, 50); } print_r($a); asort($a); $c = array_keys($a); print_r($a); $q = array(); foreach ($a as $key => $value) { $aKey = array_search($key, $c, true); if (isset($c[$aKey + 1])) { $bKey = $c[$aKey + 1]; array_unshift($q, array($value, $key, $bKey)); } } // proof-o-concept: how array can be created $r = array($key => $value); foreach ($q as $data) { echo vsprintf("Moved %s from index %d before %dn", $data); $r = array_replace(array($data[1] => $data[0]), $r); } print_r($r);
Ordering when inserting in Nested Sets tree
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).