Full of lovely web standards information and a large helping of PHP

Sorting results from PhpDelicious

1 year, 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

No comments written for this post yet. Please check back soon or consider writing the first one below!

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