简体   繁体   English

获取mysql查询返回的每个元素的计数

[英]Get count of each element returned by mysql query

This is my query: 这是我的查询:

SELECT `Brand`,`Colour`,`Occassion`,`Fabric`,`Type` 
FROM `deals` 
WHERE `Size` 
LIKE '%XS%';

It returns 35 results. 它返回35个结果。 Now, what i want is a count of each of the columns (Brand, colour etc) which are present in the above resultset to create a histogram. 现在,我想要的是上述结果集中存在的每个列(品牌,颜色等)的计数,以创建直方图。 I am not sure about how to do this. 我不确定如何执行此操作。

Any help is appreciated. 任何帮助表示赞赏。

I think ideal result should look like this: 我认为理想的结果应如下所示:

$data = array(
    "Brand" => array(brand1 => 1, brand2 => 2),
    "Colour" => array(colour1 => 1, colour2 => 2),
    "Occassion" => array(Occassion1 => 1, Occassion2 => 2),
);

For each subarray we can draw a histogram. 对于每个子数组,我们可以绘制一个直方图。 The code will look like this: 该代码将如下所示:

$query = "
SELECT
    `Brand`,`Colour`,`Occassion`,`Fabric`,`Type` 
FROM 
    `deals` 
WHERE
    `Size` LIKE '%XS%'";

$data = array(
    "Brand" => array(),
    "Colour" => array(),
    "Occassion" => array(),
    "Fabric" => array(),
    "Type" => array(),
    );

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        foreach($row as $key => $value)
        {
            $data[$key][$value]++;
        }
    }

    /* free result set */
    $result->free();
}

Or we can define $data subarrays inside foreach to make the program more flexible: 或者我们可以在foreach中定义$ data子数组,以使程序更加灵活:

$data = array();
...
    foreach($row as $key => $value)
    {
        if(!isset($data[$key]))
        {
            $data[$key] = array();
        }
        $data[$key][$value]++;
    }
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM