php - 计算关联数组中的唯一值

标签 php mysql arrays

首先,感谢您的帮助。

我在这里和其他论坛上花费了无数小时试图找到我的确切解决方案,但要么 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/

相关文章:

php - CakePHP ACL 示例

MySQL错误1215 Cannot add Foreign key constraint - FK in different tables

php - 连接 MySQL 时遇到问题

c - 从文件中读取整数并将其存储到数组中并写入文件

c - 搜索结构体数组的函数 (C)

php - 将值添加到文件中的数组并保存

php file_get_contents ("/tmp/some_file") 不工作 php7.1

php - Laravel4 中的路线 [RemindersController@postRemind] 未定义错误

php - 为 mysql 创建一个 php 变量

c - C中删除一个int *的内容