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

Sorting results from PhpDelicious

2 years, 6 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 #

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