0

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.

2
  • 1
    Do you select the columns that you want in your SQL? As it seems to me you're just selection the 'model' field thous you can only display the 'model' field. Commented Sep 20, 2017 at 9:53
  • The first line of my question states I am using select * from my table. So yes the Make column is included. Commented Sep 20, 2017 at 10:22

2 Answers 2

1

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'];

}
Sign up to request clarification or add additional context in comments.

1 Comment

I thought there must be a simpler way to it and this is it. Thank you this is perfect. Tested and working.
1

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;

    }
?>

2 Comments

Why should the OP "try this"? A good answer will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO.
Thanks, this did work but the accepted answer was better because of the explanation and changing the database query was the better approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.