function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Boulder MikeBoulder Mike 

Sorting a result set in PHP5?

I've run into the old snag that SOQL doesn't support the "ORDER BY" clause and I'm wondering if anyone has come up with a way to sort a result set from a query using PHP5.

PHP5 has a (rather complicated) function called usort that allows for user-defined sorts, but before I invest a bunch of time figuring out that function, I thought I'd throw the question out to the community.

Anyone have any other suggestions?

Another thought would be to dump the each record's fields into an array and then sort the array. That'd work, but still, it seems like a lot of pain for something so fundamental.

(I'm searching a custom object that contains a catalog of items. I'd like the items in order by item number.)
ClaiborneClaiborne

Using usort is really not that complicated. The usort function just needs another function that you use to compare the two items.

Typically, in php, your return set is an array of records. Each record also is an array. Assuming that the record array contains a column called "catalogId", the custom function would look something like this.

function CatalogSort(record1, record2) {
   if (record1['catalogId'] > record2['catalogId']) {
       return 1;
   }
   else {
       return -1;
   }
}

alternately

function CatalogSort(record1, record2) {
   return (record1['catalogId'] > record2['catalogId']) ? 1 : -1;
}

Using the usort function, the call would be:

$sortedRecords = usort($records, "CatalogSort");

Boulder MikeBoulder Mike
Thanks David. I thought it'd be more complicated but I'm glad to see your example.
Boulder MikeBoulder Mike
With a couple of tweaks, I have it working nicely. (Thanks again, David!)

function CatalogSort( $record1 , $record2 ) {
if ( $record1->ItemNo > $record2->ItemNo ) {
return 1;
} else {
return -1;
}
}

When you call usort, it sorts the records within the variable -- it doesn't appear to return the sorted object.

usort( $catalogRecords, "CatalogSort" );