Group by count in percentage from SQL resultset & PHP work

I have a visitors’ table with the country and the total number of visitors.

I am getting results from the below query country and visitors count.

I want to know % of visitors from by country.

SELECT distinct country, count(*) as count FROM visitors
GROUP BY country
ORDER BY count DESC

For example

USA 1000
France 500
Italy 600
Germany 900

I need

USA 50%
France 30%
Italy 20%
Germany 80%

I think I need to calculate the percentage in PHP based on the total count of visitors.

Like (10/100)*100 = 10% but when the visitor’s max count is 175060, how to decide out of total % I mean 100 in the previous calculation.

That would be the sum of all values.

Assuming an array $values with keys country and count it would be something like this:

$total = array_sum(array_column($values, 'count'));

foreach ($values as $country => $visits) {
    printf('%s %.2f %%', $country, ($visits / $total) * 100);
}
1 Like

Sorry this makes no sense. You have 3000 Customers in total and USA has 1000. So its 33% and not 50% or?

Many thanks, friends for your support. The problem is solved.