这是我的查询:
SELECT `Brand`,`Colour`,`Occassion`,`Fabric`,`Type`
FROM `deals`
WHERE `Size`
LIKE '%XS%';
它返回 35 个结果。现在,我想要的是对上述结果集中存在的每一列(品牌、颜色等)进行计数,以创建直方图。我不确定如何做到这一点。
任何帮助表示赞赏。
我认为理想的结果应该是这样的:
$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]++;
}
...