计算关联数组的唯一值 [英] Count unique value from associative array

查看:60
本文介绍了计算关联数组的唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,感谢您的帮助。

我在这里和其他论坛上花费了无数小时,试图找到确切的解决方案,但要么1)我都不了解我已经读过的书或2)我没有找到正确的答案。

I've spent countless hours on here and other forums trying to find my exact solution but either 1) I'm not understanding the one's I've read or 2)I haven't found the right answer.

在PHP中,我运行了一个稍微复杂的查询,该查询返回了一组记录类似于:

In PHP, I've run a somewhat complex query which returns a set of records similar to:

id | name | direction| 
1    aaa    east
2    bbb    west
3    ccc    east

我创建了一个关联数组,例如:

I've created an associative array such as:

$query=("select * from foo");
$result=mysql_query($query);
$array=mysql_fetch_assoc($result);

现在,我需要做的事情似乎很简单,但是由于某种原因我没有掌握这个概念。
我需要遍历整个$ array并返回要指定的任何值的计数并将该计数存储在变量中。

Now, what I need to do seems simple but I'm not grasping the concept for some reason. I need to loop through the entire $array and return a count of any value that I want to specify and store that count in a variable.

即请告诉我 east 在方向列中显示了多少次,并将其放在名为 $ eastcount 的变量中。

i.e. Show me how many times east shows up in the "direction" column and put that in a variable called $eastcount.

我尝试了使用 foreach 循环和增量计数的各种组合,并尝试了使用 array_count_values ,但无法将它们组合在一起:/

I've tried various combinations of using foreach loops with incremental counts and have tried using array_count_values but have not been able to put the pieces together :/

推荐答案

// build query
$query=("select * from foo");

// execute query
$result=mysql_query($query);

// declare vars
$east_count = 0;

// iterate through results
while ($data = mysql_fetch_array($result)) {

    // grab DIRECTION column value
    $direction = $data['direction'];

    // detect 'east'
    if ($direction == 'east') {

        // increment 'east' count
        $east_count++;
    }
}

// print # of times we had 'east'
echo("direction said 'east' $east_count times");

这篇关于计算关联数组的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆