Fun with Views and Feeds: Sorting feeds based on number of items

Here's a short recipe to sort the results of a view using PHP. The domain of application is sorting feeds in Managing News based on the number of items each feed has.

<?php
// @file mymodule.module
/**
 * Implementation of hook_views_pre_render().
 */
function mymodule_views_pre_render(&$view) {
  if (
$view->name == 'myview_name') {
   
$nids = array();
    foreach (
$view->result as $result) {
     
$nids[] = $result->{$view->base_field};
    }
    if (empty(
$nids)) return;
   
$result = db_query("
SELECT feed_nid, COUNT(*) AS count
FROM {feeds_data_syndication}
WHERE feed_nid IN (%s)
GROUP BY feed_nid
    "
, implode(',', $nids));
   
$counts = array();
    while (
$count = db_fetch_array($result)) {
     
$counts[$count['feed_nid']] = $count['count'];
    }
   
usort($view->result, Functor::create_functor('_mymodule_compare_counts', $counts, $view->base_field));
  }
}

function
_mymodule_compare_counts($a, $b, $counts, $base_field) {
  return
$counts[$b->$base_field] - $counts[$a->$base_field];
}
?>

You can find the code for class Functor in an earlier post.

Note: Whereas we're currently using hook_views_pre_render to perform this functionality, the more correct approach would be to post-process the view results right after execution. The problem is that hook_views_post_execute does not exist - but it will if this issue goes through!

Comments

COUNT(*) will be

COUNT(*) will be significantly faster than COUNT(id).

Thanks, I've changed it here

Thanks, I've changed it here and in the original code.