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

时间:2013-07-25 21:28:40

标签: php mysql count histogram

这是我的疑问:

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

它返回35个结果。现在,我想要的是每个列(品牌,颜色等)的计数,它们存在于上面的结果集中以创建直方图。我不确定如何做到这一点。

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我认为理想的结果应该是这样的:

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

对于每个子阵列,我们可以绘制直方图。代码如下所示:

$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();
}

或者我们可以在foreach中定义$ data子数组,以使程序更加灵活:

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