简体   繁体   English

打印数组键和值

[英]Print array keys and values

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”的表,其中人的名字与他们的城市相关联,我需要检索来自同一城市的人数。

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? 还有其他选择吗?

That's just the output from print_r() . 那只是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". 除了print_r()之外,还有var_dump()var_export() ,它们都是“调试功能”。 So use them for debugging and not for printing "nice formatted output". 因此,将它们用于调试,而不是用于打印“格式良好的输出”。

You need to use the MySQL function COUNT(*) & the GROUP BY clause: 您需要使用MySQL函数COUNT(*)和GROUP BY子句:

$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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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