Danielle Rose Mabunga
Danielle Rose Mabunga

Reputation: 1724

Sort array by count results in Php

I want to sort the result based on a result count in php loop.My code in templates looks like this

<?php foreach($groups as $group): ?>
        <?php if(count($group->getAllgroupmember()) > 0): ?>
            <tr>
                <td><?php echo $group->id ?></td>
                <td><?php echo $group->name ?></td>
                <td><?php echo number_format(count($group->getAllgroupmember())) ?></td>
            </tr>
        <?php endif ?>
        <?php var_dump(count($group->getAllgroupmember())) ?>
    <?php endforeach ?>

The var_dump result

int(1) int(1) int(4) int(0) int(1) int(0) int(0) int(0) int(0) int(0) int(1) int(0) int(0) int(0) int(0) int(0) int(0) int(0) int(0) int(0) int(0) int(0) int(0) int(0)

How to sort based on result count? The highest value(4) should be in 0 position. I tried usort function

<?php foreach(usort($groups) as $group): ?>
        <?php if(count($group->getAllgroupmember()) > 0): ?>
            <tr>
                <td><?php echo $group->id ?></td>
                <td><?php echo $group->name ?></td>
                <td><?php echo number_format(count($group->getAllgroupmember())) ?></td>
            </tr>
        <?php endif ?>
        <?php var_dump(count($group->getAllgroupmember())) . "<br>" ?>
    <?php endforeach ?>

But no luck..Any ideas how fullfill this?

Upvotes: 1

Views: 278

Answers (1)

dlporter98
dlporter98

Reputation: 1630

usort requires a callable as the second parameter. See below:

<?php
$usort($groups, function($a, $b){
    $countA = count($a->getAllgroupmember());
    $countB = count($b->getAllgroupmember());
    if ($countA  == $countB) {
        return 0;
    }
    return ($countA > $countB) ? -1 : 1;
});
?>
<?php foreach($groups as $group): ?>
        <?php if(count($group->getAllgroupmember()) > 0): ?>
            <tr>
                <td><?php echo $group->id ?></td>
                <td><?php echo $group->name ?></td>
                <td><?php echo number_format(count($group->getAllgroupmember())) ?></td>
            </tr>
        <?php endif ?>
        <?php var_dump(count($group->getAllgroupmember())) . "<br>" ?>
    <?php endforeach ?>

The sort function I crafted above gets the member count for each of the passed in objects and sorts the array using those numbers in descending order.

I've added a link to the usort method above. You should be able to further understand the function I crafted after you review the usort documentation.

I hope this helps.

Upvotes: 2

Related Questions