首先,感谢您的帮助。
我在这里和其他论坛上花费了无数小时试图找到我的确切解决方案,但要么 1) 我不理解我读过的那些,要么 2) 我没有找到正确的答案。
在 PHP 中,我运行了一个有点复杂的查询,它返回一组类似于以下内容的记录:
id | name | direction|
1 aaa east
2 bbb west
3 ccc east
我创建了一个关联数组,例如:
$query=("select * from foo");
$result=mysql_query($query);
$array=mysql_fetch_assoc($result);
现在,我需要做的事情看起来很简单,但由于某种原因我没有掌握这个概念。 我需要遍历整个 $array 并返回我想要指定的任何值的计数,并将该计数存储在一个变量中。
即显示 east 在“方向”列中出现了多少次,并将其放入名为 $eastcount
的变量中。
我尝试了使用 foreach
循环和增量计数的各种组合,并尝试使用 array_count_values
但无法将各个部分组合在一起:/
最佳答案
// 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");
关于php - 计算关联数组中的唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14970869/