note 76602 added to function.sort

From: Date: Sun, 22 Jul 2007 12:42:10 +0000
Subject: note 76602 added to function.sort
Groups: php.notes 
Request: Send a blank email to php-notes+get-128814@lists.php.net to get a copy of this message
Hi, this is my version of sorting an array by field. From browsing previous versions it pretty much resembles bluej's version. It's way much faster than the versions where the sorting is made "manually" rather than with native php functions, and I wrote it after trying one of those that kept timing out my scripts if I had 10000 posts. This one preserves numerical keys as well. So if you want to re-index the array after using it with numerical keys just use the array_values on the result. However there are cases where the key actually means something even if it's a number (id etc) so I didn't want to take it for granted that it should be reindexed. Cheers Q <?php function sortArrayByField ( $original, $field, $descending = false ) { $sortArr = array(); foreach ( $original as $key => $value ) { $sortArr[ $key ] = $value[ $field ]; } if ( $descending ) { arsort( $sortArr ); } else { asort( $sortArr ); } $resultArr = array(); foreach ( $sortArr as $key => $value ) { $resultArr[ $key ] = $original[ $key ]; } return $resultArr; } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 83.140.180.193 ---- Manual Page -- http://www.php.net/manual/en/function.sort.php Edit -- https://master.php.net/note/edit/76602 Del: integrated -- https://master.php.net/note/delete/76602/integrated Del: useless -- https://master.php.net/note/delete/76602/useless Del: bad code -- https://master.php.net/note/delete/76602/bad+code Del: spam -- https://master.php.net/note/delete/76602/spam Del: non-english -- https://master.php.net/note/delete/76602/non-english Del: in docs -- https://master.php.net/note/delete/76602/in+docs Del: other reasons-- https://master.php.net/note/delete/76602 Reject -- https://master.php.net/note/reject/76602 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#128814) next »