PHP如何从数组中输出top array_count_values值?

时间:2014-03-05 16:01:29

标签: php arrays count

我有一个表,我需要找到“顶级可信赖的构建器”,Trusts用“;”分隔,所以我需要提取所有数据,爆炸用户名,订购和计算它们,我终于坚持了从数组中输出顶级用户名,我已经发布了PHP的完整部分,因为我确定必须有更好的方法来实现这一点。

<?php 
$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');
$GMCB->setFetchMode(PDO::FETCH_ASSOC);

$buildersarray = array();

while($row = $GTB->fetch()) {

      $allbuilders = explode(";", $row['builders']);
        for($i = 0; $i < count($allbuilders); $i++)
          {
            $buildersarray[] = $allbuilders[$i];
          }
}

echo "<pre>";
print_r(array_count_values(array_filter($buildersarray)));
echo "</pre>";
?>

输出

Array
(
[username1] => 4
[username2] => 1
[username3] => 1
)

2 个答案:

答案 0 :(得分:1)

您可以将array_count_values命令中的数组返回到名为$ topbuilders的新数组中,然后回显当前(第一个)记录:

$topbuilders = array_count_values(array_filter($buildersarray));
echo current(array_keys($topbuilders)).', Rank = '.current($topbuilders);

current()将返回关联数组中的第一项。

答案 1 :(得分:0)

不使用array_count_values(),最好使用名称作为频率数组的关键字:

$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');

$result = array();

while (($builders = $GTB->fetchColumn()) !== false) {
    foreach (explode(";", $builders) as $builder) {
        if (isset($result[$builder])) {
            $result[$builder]++;
        } else {
            $result[$builder] = 1;
        }
}
// sort descending based on numeric comparison
arsort($result, SORT_NUMERIC);

echo "Name = ", key($result), " Count = ", current($result), "\n";