Re: A better way to sort?

From: Date: Wed, 23 Apr 2003 20:26:33 +0000
Subject: Re: A better way to sort?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-145075@lists.php.net to get a copy of this message
On Wed, 23 Apr 2003, Steve Keller wrote: > I've just written a function to do what I want, but I thought I'd offer up > my problem and see who has a better idea, because the way I did it seems > clunky to me at best. You can sort that pretty easily and cleanly using usort(), and save all the implode()s and explode()s. I bloated this response with the data storage and retrieval just be be complete, not because I missed that you're reading from a file -- just stash the sort function (it's hella resuable for sorting nested arrays like this), set $sortField and $sortDirection, and make the call to usort() ... your data is sorted. <?php // (FAKED) THE DATA FROM YOUR FILE $fileData = array( "chris--wesley--3000001--newark", "mark--humphries--2521119--san bernadino", "bob--jones--3335555--pittsburgh" ); // (FAKED) READ THE DATA FROM YOUR FILE $arrayData = array(); foreach( $fileData as $record ){ array_push( $arrayData, explode( "--", $record ) ); } // *** HERE'S THE PART THAT ANSWERS YOUR QUESTION *** // NIFTY SORT FUNCTION TO USE WITH usort() -> http://php.net/usort // TO SORT NESTED ARRAYS function data_usort( $arrayA, $arrayB ){ global $sortField, $sortDirection; if( $arrayA[$sortField] == $arrayB[$sortField] ) return( 0 ); if( $sortDirection == "a" ) return( $arrayA[$sortField] > $arrayB[$sortField] ? 1 : -1 ); if( $sortDirection == "d" ) return( $arrayA[$sortField] < $arrayB[$sortField] ? 1 : -1 ); } // THESE GET PICKED UP BY THE SORT FUNCTION FROM GLOBAL NAMESPACE $sortField = 2; // THE FIELD ON WHICH TO SORT $sortDirection = 'a'; // SORT DIRECTION a=ascending, d=descending // SORT THE DATA usort( $arrayData, "data_usort" ); // SWEET var_dump( $arrayData ); ?> It's interesting to see your type of question. Most people throw a database at this problem -- some, for good reason. Hope this solution helps your situation. Good luck, ~Chris

« previous php.general (#145075) next »