1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.