简体   繁体   中英

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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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