简体   繁体   English

在Php中按计数结果对数组进行排序

[英]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 loop中的结果计数对结果进行排序。我的模板中的代码如下所示

<?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 var_dump结果

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. 最大值(4)应该在0位置。 I tried usort function 我尝试过usort函数

<?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? 但是没有运气..任何想法如何实现这一目标?

usort requires a callable as the second parameter. usort需要一个callable作为第二个参数。 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. 我上面编写的sort函数获取每个传入对象的成员计数,并使用这些数字以降序对数组进行排序。

I've added a link to the usort method above. 我在上面的usort方法中添加了一个链接。 You should be able to further understand the function I crafted after you review the usort documentation. 在查看usort文档之后,您应该能够进一步理解我制作的功能。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM