php - 计算行和列中相同的数字 php mysql

标签 php mysql

我有这样的 MySql 表:

+----+----+----+
| g1 | g2 | g3 |
+----+----+----+
| 1  | 2  | 5  |
+----+----+----+
| 5  | 1  | 3  |
+----+----+----+
| 1  | 3  | 4  |
+----+----+----+

我需要在 PHP 中获取输出,例如:

number 1 is used 4 times
number 2 is used 1 time
number 3 is used 2 times

我编写了一些代码,但它只写了我使用该号码的次数,而且我不知道如何添加哪个号码。 这是我的代码:

for ( $i=1 ; $i<=20; $i++){

            $query = mysql_query("SELECT g1, g2, g3d FROM users 
            WHERE g1 = $i OR g2 = $i OR g3 = $i ") or die(mysql_error()) ;

            $row1 = mysql_num_rows($query);

        $row = mysql_fetch_array($query)    ;
            if ($row1 >=1){echo $row1; }
        }

感谢您的帮助。

最佳答案

我建议这样做:

// Will be used to keep track of how many times a certain number has appeared
$counter = array();

// Just get all of the rows from the table
$query = mysql_query("SELECT g1, g2, g3 FROM users");

// Loop all rows
while($row = mysql_fetch_assoc($query))
{
    // Loop each column: g1, g2, and g3
    foreach($row as $k=>$v)
    {
        // Use the column's value as the array key and let the value be the count of occurrences
        $counter[$v] = (isset($counter[$v]) ? ++$counter[$v] : 1);
    }
}

// Sort based on key from low to hi
ksort($counter);

// Loop the tracker and echo whatever you need
foreach($counter as $k=>$v)
{
    echo 'number '.$k.' is used '.$v.' time'.($v === 1 ? '' : 's').'<br>';
}

关于php - 计算行和列中相同的数字 php mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37976463/

相关文章:

php - php 变量中的 Javascript 代码

sql - 在 SQL 中将一个值除以其平均值

mysql - 数据库引用表

php - 提供的参数不是有效的MySQL结果资源错误

mysql - 需要 MYSQL 查询仅选择特定子行

php - 如何使用 php、mysql、css、jquery 和 html 创建简单的网站?

php - 使用 HTML 表单和 PHP 在 MySQL 数据库中存储电子邮件

php - Laravel:如何使路由助手返回带有尾部斜杠的 URL?

php - 在 php 或 javascript 中构建 html 结构?

mysql db records visibility (design and select help)