note 87032 modified in function.sort by danbrown

From: Date: Sun, 16 Nov 2008 17:41:09 +0000
Subject: note 87032 modified in function.sort by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-146600@lists.php.net to get a copy of this message
this is an implementation of the complement of Matthew Hood's objectSort (http://my.php.net/manual/en/function.sort.php#75036), which i found very convenient for sorting objects. this does the reverse, it sorts according to the key selected for the object but in reverse order. and having both sort methods allows consistency and convenience for sorting objects, if speed isn't your major concern. the only change ( apart form data being reworded as object ) is the use of < instead of > in the original. you could of couse incorporate all in one routine, but why complicate matters. <?php function objectRSort(&$object, $key) { for ($i = count($object) - 1; $i >= 0; $i--) { $swapped = false; for ($j = 0; $j < $i; $j++) { if ($object[$j]->$key < $object[$j + 1]->$key) { $tmp = $object[$j]; $object[$j] = $object[$j + 1]; $object[$j + 1] = $tmp; $swapped = true; } } if (!$swapped) return; } } ?> --was-- this is an implementation of the complement of Matthew Hood's objectSort (http://my.php.net/manual/en/function.sort.php#75036), which i found very convenient for sorting objects. this does the reverse, it sorts according to the key selected for the object but in reverse order. and having both sort methods allows consistency and convenience for sorting objects, if speed isn't your major concern. the only change ( apart form data being reworded as object ) is the use of < instead of > in the original. you could of couse incorporate all in one routine, but why complicate matters. function objectRSort(&$object, $key) { for ($i = count($object) - 1; $i >= 0; $i--) { $swapped = false; for ($j = 0; $j < $i; $j++) { if ($object[$j]->$key < $object[$j + 1]->$key) { $tmp = $object[$j]; $object[$j] = $object[$j + 1]; $object[$j + 1] = $tmp; $swapped = true; } } if (!$swapped) return; } } http://php.net/manual/en/function.sort.php

« previous php.notes (#146600) next »