简体   繁体   中英

How can I count array values from mysql query in PHP and associate a second column with the count results

What I am trying to do is select * from table then get the count of duplicate rows in a column but also have another column (make) associated with the results.

Eg:

Desired output:

Make Model Qty

Ford Focus 3

Ford Fiesta 5

Ford Mondeo 1

BMW M3 1

Audi A4 2

Audi A3 4

Current output:

Model Qty

Focus 3

Fiesta 5

Mondeo 1

M3 1

A4 2

A3 4

My code:

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$modelArray = [];

foreach ($rows as $row) {

    $modelArray[] = $row['model'];

}

$result = array_count_values($modelArray);

foreach ($result as $model=>$qty) {

    echo $model." ".$qty;

}

I don't know how to also include the 'make' column in my results using the array_count_values() function.

I think I may be going about this the wrong way as it would appear to be a fairly common task but I can't find any information on how to do it like this.

Any help would be greatly appreciated thanks.

Try this

<?php 
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $modelArray = [];
    $makes = []
    foreach ($rows as $row) {

        $modelArray[] = $row['model'];
        $makes[$row['model']]=$row['make'];

    }

    $result = array_count_values($modelArray);

    foreach ($result as $model=>$qty) {

        echo $makes[$model]." ".$model." ".$qty;

    }
?>

I guest what you are trying to do is a GROUP BY statement. Here
I guest your current query is SELECT make, model FROM table .
Then you count repeating data using array_count_values . I think you need to change the query using GROUP BY statement like this.

SELECT make, model, COUNT(1) AS qty FROM table GROUP BY make, model

Using that query, you can echo the result using this code.

foreach ($rows as $row) {

    echo $row['make'] . " " . $row['model'] . " " . $row['qty'];

}

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