-1

I am trying to sort an array from high to low.

The query is written in an Joomla module and is this one:

$authors = array();
    if (count($rows))
    {
        foreach ($rows as $row)
        {
            $author = JFactory::getUser($row->created_by);
            $author->link = JRoute::_(K2HelperRoute::getUserRoute($author->id));

            $query = "SELECT id, gender, description, image, url, `group`, plugins FROM #__k2_users WHERE userID=".(int)$author->id;
            $db->setQuery($query);
            $author->profile = $db->loadObject();

            if ($params->get('authorAvatar'))
            {
                $author->avatar = K2HelperUtilities::getAvatar($author->id, $author->email, $componentParams->get('userImageWidth'));
            }

            if (K2_JVERSION != '15')
            {
                $languageCheck = '';
                if ($application->getLanguageFilter())
                {
                    $languageTag = JFactory::getLanguage()->getTag();
                    $languageCheck = "AND i.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').") AND c.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').")";
                }
                $query = "SELECT i.*, c.alias as categoryalias FROM #__k2_items as i
                LEFT JOIN #__k2_categories c ON c.id = i.catid
                WHERE i.created_by = ".(int)$author->id."
                AND i.published = 1
                AND i.access IN(".implode(',', $user->getAuthorisedViewLevels()).")
                AND ( i.publish_up = ".$db->Quote($nullDate)." OR i.publish_up <= ".$db->Quote($now)." )
                AND ( i.publish_down = ".$db->Quote($nullDate)." OR i.publish_down >= ".$db->Quote($now)." )
                AND i.trash = 0 AND created_by_alias='' AND c.published = 1 AND c.access IN(".implode(',', $user->getAuthorisedViewLevels()).") AND c.trash = 0 {$languageCheck} ORDER BY created DESC";
            }
            else
            {
                $query = "SELECT i.*, c.alias as categoryalias FROM #__k2_items as i
                LEFT JOIN #__k2_categories c ON c.id = i.catid
                WHERE i.created_by = ".(int)$author->id."
                AND i.published = 1
                AND i.access <= {$aid}
                AND ( i.publish_up = ".$db->Quote($nullDate)." OR i.publish_up <= ".$db->Quote($now)." )
                AND ( i.publish_down = ".$db->Quote($nullDate)." OR i.publish_down >= ".$db->Quote($now)." )
                AND i.trash = 0 AND created_by_alias='' AND c.published = 1 AND c.access <= {$aid} AND c.trash = 0 ORDER BY created DESC";
            }

            $db->setQuery($query, 0, 1);
            $author->latest = $db->loadObject();
            $author->latest->id = (int)$author->latest->id;
            $author->latest->link = urldecode(JRoute::_(K2HelperRoute::getItemRoute($author->latest->id.':'.urlencode($author->latest->alias), $author->latest->catid.':'.urlencode($author->latest->categoryalias))));

            $query = "SELECT COUNT(*) FROM #__k2_comments WHERE published=1 AND itemID={$author->latest->id}";
            $db->setQuery($query);
            $author->latest->numOfComments = $db->loadResult();

            if ($params->get('authorItemsCounter'))
            {
                if (K2_JVERSION != '15')
                {
                    $languageCheck = '';
                    if ($application->getLanguageFilter())
                    {
                        $languageTag = JFactory::getLanguage()->getTag();
                        $languageCheck = "AND language IN (".$db->Quote($languageTag).", ".$db->Quote('*').")";
                    }
                    $query = "SELECT COUNT(*) FROM #__k2_items  WHERE {$where} published=1 AND ( publish_up = ".$db->Quote($nullDate)." OR publish_up <= ".$db->Quote($now)." ) AND ( publish_down = ".$db->Quote($nullDate)." OR publish_down >= ".$db->Quote($now)." ) AND trash=0 AND access IN(".implode(',', $user->getAuthorisedViewLevels()).") AND created_by_alias='' AND created_by={$row->created_by} {$languageCheck} AND EXISTS (SELECT * FROM #__k2_categories WHERE id= #__k2_items.catid AND published=1 AND trash=0 AND access IN(".implode(',', $user->getAuthorisedViewLevels()).") {$languageCheck} )";
                }
                else
                {
                    $query = "SELECT COUNT(*) FROM #__k2_items  WHERE {$where} published=1 AND ( publish_up = ".$db->Quote($nullDate)." OR publish_up <= ".$db->Quote($now)." ) AND ( publish_down = ".$db->Quote($nullDate)." OR publish_down >= ".$db->Quote($now)." ) AND trash=0 AND access<={$aid} AND created_by_alias='' AND created_by={$row->created_by} AND EXISTS (SELECT * FROM #__k2_categories WHERE id= #__k2_items.catid AND published=1 AND trash=0 AND access<={$aid} ) ";
                }
                $db->setQuery($query);
                $numofitems = $db->loadResult();
                $author->items = $numofitems;
            }

            $authors[] = $author;

        }
    }


    return $authors;
}

then the result is passing to these variables and finally authors table is returned. This table I want to sort from high to low. I have tried the php functions but none of them seem to working.

I cannot be sure if the query retrieves something else beyond the items counter and set it as key. But I have tried functions such as arsort which is sorting by value and not key.

$db->setQuery($query);
$numofitems = $db->loadResult();
$author->items = $numofitems;
$authors[] = $author;
arsort($authors);

Any idea is appreciated

Thank you

giorgionasis
  • 394
  • 1
  • 7
  • 17
  • When you have Joomla questions, please post them at [joomla.se] Stack Exchange. You should be building your queries with Joomla's query building methods. – mickmackusa Feb 05 '19 at 04:36
  • Your code can be refactored to condense your conditional query build. `$where` is a mystery. In fact it looks likely that you can combine some a couple of your queries to avoid much of this convoluted code. – mickmackusa Feb 05 '19 at 04:52
  • and this page with no upvoted answer: https://stackoverflow.com/q/24956420/2943403 – mickmackusa Feb 05 '19 at 05:08
  • @mickmackusa of course the class is not optimized but it is a build in module of joomla so I have no written it. Before I post, believe me i tried everything. But I am not a sound developer neither I have experience with arrays (keys,valus,objects). So according to the answers I cannot distinguish if I should replace $author with $a or $items with $a – giorgionasis Feb 05 '19 at 08:42
  • You should implement jspcal's solution after the loop on `$authors`. – mickmackusa Feb 05 '19 at 08:59
  • I did it and it worked!No I am working around how to get right order because I have this one: 1 1 1 12 2 2 23 3 3 31 4. Any idea? – giorgionasis Feb 05 '19 at 09:01
  • You require natural sorting `$author->items = (int)$numofitems;` This stores them as integers not strings. – mickmackusa Feb 05 '19 at 09:06
  • function cmp($a, $b) { return $b->items - $a->items; } usort($authors, "cmp"); this one make the job! – giorgionasis Feb 05 '19 at 09:30
  • 1
    Don't compare their string values, use jspcal's solution. Furthermore don't share images of code here (ever), we always want to work with text in case we want to copy-paste. 3v4l.org is a good one to use. – mickmackusa Feb 05 '19 at 09:31

1 Answers1

1

Generally database queries can be sorted by specifying an order as in

$query->order('my_table.my_column desc')

If you're sorting a PHP array and require a custom sort criteria, you can use your own sort criteria with usort. For example:

// Your comparison function:

function myComparer($object1, $object2)
{
    if ($object1->item == $object2->item) {
       return 0;
    }

    return ($object1->item < $object2-item) ? -1 : 1;
}

// Sort the array in place

usort($authors, 'myComparer');

Note you can reverse the order of the sort by simply swapping the comparison return values:

return ($object1->itemCount < $object2-itemCount) ? 1 : -1;
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
jspcal
  • 50,847
  • 7
  • 72
  • 76
  • thank you for your advice but the above code give me a blank page Warning: usort() expects parameter 1 to be array, object given in /home/proteino/public_html/modules/mod_k2_tools/helper.php on line 167 Fatal error: Cannot redeclare myComparer() (previously declared in /home/proteino/public_html/modules/mod_k2_tools/helper.php:156) in /home/proteino/public_html/modules/mod_k2_tools/helper.php on line 156 – giorgionasis Feb 04 '19 at 22:53
  • You should be passing an array to usort. And don't include the function twice. – jspcal Feb 04 '19 at 23:01
  • I tried with every possible combination usort ($authors, 'myCoparer') usort ($authors[], 'myCoparer') usort ($author, 'myCoparer') usort ($author[], 'myCoparer') nothing is working. – giorgionasis Feb 04 '19 at 23:07
  • If i simply use arsort, the table is sorting but not according to $author->items = $numofitems; but according something else – giorgionasis Feb 04 '19 at 23:08
  • You spelled 'myComparer' wrong. – jspcal Feb 04 '19 at 23:48
  • function cmp($a, $b) { return $b->items - $a->items; } usort($authors, "cmp"); this one make the job! – giorgionasis Feb 05 '19 at 09:31