0

Given a table called "people" where names of people are associated to their city, I need to retrieve the number of people who come from the same city.

PEOPLE CITY John Baltimore David London Paula Baltimore Mark Baltimore Alex London 

My code is as follows:

$array_cities = array(); $query = "SELECT * FROM people"; $result = mysql_query($query); if ($result) { while ($record = mysql_fetch_array($result)) $array_cities[] = $record['city']; } print_r(array_count_values($array_cities)); 

And what I get in my browser is:

Array ( [Baltimore] => 3 [London] => 2 ) 

The output is correct, but it is not graphically good. What I would want is something like:

Baltimore => 3 London => 2 

Are there any other options to get it?

3
  • 1
    Loop it and correct graphically good Commented Jul 8, 2015 at 11:51
  • So where are we with this question ? Commented Jul 8, 2015 at 12:16
  • Rizier, your answer worked like a charm. Commented Jul 8, 2015 at 12:27

2 Answers 2

2

That's just the output from print_r(). If you want something else, just loop through the array an print it:

foreach(array_count_values($array_cities) as $k => $v) echo $k . " => " . $v . " "; 

Sidenote:

Besides print_r() there are also var_dump() and var_export(), which are all "debugging functions". So use them for debugging and not for printing "nice formatted output".

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

Comments

0

You need to use the MySQL function COUNT(*) & the GROUP BY clause:

$array_cities = array(); $query = 'SELECT COUNT(*) AS `persons`, `city` FROM `people` GROUP BY `city`'; $result = mysql_query($query); if ($result) { while ($record = mysql_fetch_array($result)) { $array_cities[$record['city']] = $record['persons']; } } print_r($array_cities); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.