Pressure is nothing more than the shadow of great opportunity. - Michael Johnson

Sorting results from PhpDelicious

3 years, 8 months ago

Someone emailed me today to ask me how they could sort results, returned from my PhpDelicious class, alphabetically by description. It seems to me that the solution would probably be useful to other people hence the post.

  1. <?php
  2. require('php-delicious.inc.php');
  3. function SortByDesc($sA, $sB) {
  4. return strcmp($sA['desc'], $sB['desc']);
  5. }
  6. $oDelicious = new PhpDelicious(YOUR_USERNAME, YOUR_PASSWORD);
  7. if ($aPosts = $oDelicious->GetAllPosts()) {
  8. usort($aPosts, 'SortByDesc');
  9. echo "<ul>";
  10. foreach ($aPosts as $aPost) {
  11. echo "<li><a href=\"{$aPost['url']}\">{$aPost['desc']}</a></li>";
  12. }
  13. echo "</ul>";
  14. }
  15. ?>

It uses the usort function which sorts array values using a user-defined comparison function - in this case SortByDesc. This custom function uses strcmp, which does a case sensitive string comparison, to determine which parameter should appear first. If you want to do a case insensitive comparison instead replace strcmp function with strcasecmp.

strncmp and strncasecmp which compare the first n characters of each word, case-sensitively and case-insensitively respectively, are also worth a look.

Comments

  • exactly what I am looking for! thanks for sharing about this Ed! I'm too noob in programming and I can't figure this out myself without your tutorial.

    *bows down*

    Jehzeel Laurente - 29th May 2009 #

  • Hi - can you help? Bit of a noob, but I downloaded and copied phpdelicious to use on a project - using the code above. But viewing the page I get this error:

    Notice: Use of undefined constant CACHE_PATH - assumed 'CACHE_PATH' in C:\wamp\www\testing\cache.inc.php on line 44

    Any ideas? Thanks...

    Meander365 - 17th April 2010 #

Help make this post better

Notes: Standard BBCode for links, bold, italic and code are supported. rel="nofollow" is added to all links. Your email address will never be displayed on the site.

Back to index