在 MYSQL PHP 中对城市、州和国家进行分组

发布于 2024-12-03 04:16:04 字数 1517 浏览 2 评论 0原文

我是 PHP 新手,为此访问了几个网站,但似乎无法彻底理解。

我有这个查询:

$result = mysql_query
  ("SELECT Country, State, City
       FROM Address_Base
       ORDER BY Country, State, City")
  or die(mysql_error());

这给出了以下数据样本:

加拿大 - 州 1 - 苹果市

加拿大 - 州 2 - 城市葡萄

加拿大 - 州 1 - 苹果市

加拿大 - 州 2 - 城市咖啡

美国 - 州 1 - 城市斑马

美国 - 州 2 - 城市猫

美国 - 州 2 - 城市之狮

美国 - 州 3 - 城市鸟

美国 - 州 1 - 城市斑马

我的目标是将各个州下的城市分组并计算城市,将各个国家/地区下的州分组将相似的国家分组并生成类似的内容

Canada -
{
  State 1 - City Apple (2)
  State 2 - City Coffee (1), City Grapes (1)
}

USA -
{
    State 1 - City Zebra (2)
    State 2 - City Cat (1), City Lion (1)
    State 3 - City Bird (1)
}

从其他一些网站,我得到了:

$combinedResults = array();

while ($rec=mysql_fetch_assoc($result))
{
    $combinedResults[$rec['Country']][] = array
            (               
                'S' => $rec['State'], 
                'C' => $rec['City']
            );                           
}

foreach(array_keys($combinedResults) as $Country)
{ 
    echo '<div class="country">'.$Country.'</div>';

    foreach($combinedResults[$Country] as $Set)
    { 
        echo $Set['S'].'<br/>'.$Set['C'].'<br/><br/>'; 
    } 
} 

这仅对相似的国家进行分组,而不对州和城市进行分组。我猜上面的代码正在尝试预处理某种多维数组中的数据,并有一个 for 循环显示结果。我无法清楚地理解它。

如果有人能为我解释一下,以及我如何进一步按照上述要求分别对州和城市进行分组,我将非常感激?

I am new to PHP and have visited several sites for this but can't seem to understand thoroughly.

I have this query:

$result = mysql_query
  ("SELECT Country, State, City
       FROM Address_Base
       ORDER BY Country, State, City")
  or die(mysql_error());

This gives the following data sample:

Canada - State 1 - City Apple

Canada - State 2 - City Grapes

Canada - State 1 - City Apple

Canada - State 2 - City Coffee

USA - State 1 - City Zebra

USA - State 2 - City Cat

USA - State 2 - City Lion

USA - State 3 - City Bird

USA - State 1 - City Zebra

My goal is to group the cities under the respective state and count city, group the states under the respective country & group similar countries and produce something like this

Canada -
{
  State 1 - City Apple (2)
  State 2 - City Coffee (1), City Grapes (1)
}

USA -
{
    State 1 - City Zebra (2)
    State 2 - City Cat (1), City Lion (1)
    State 3 - City Bird (1)
}

From some other site, I got this:

$combinedResults = array();

while ($rec=mysql_fetch_assoc($result))
{
    $combinedResults[$rec['Country']][] = array
            (               
                'S' => $rec['State'], 
                'C' => $rec['City']
            );                           
}

foreach(array_keys($combinedResults) as $Country)
{ 
    echo '<div class="country">'.$Country.'</div>';

    foreach($combinedResults[$Country] as $Set)
    { 
        echo $Set['S'].'<br/>'.$Set['C'].'<br/><br/>'; 
    } 
} 

This only groups similar Countries and not states and the cities. I guess the above piece of code is trying to pre-process the data in some sort of multi-dimensional array and have a for loop display the results. I am not able to understand it clearly.

I would be very thankful if someone could explain it for me and how I can further group the states and cities respectively as sought above?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ˉ厌 2024-12-10 04:16:05
$result = mysql_query('SELECT Country, State, City From Address_Base ORDER BY Country, State, City') or die(mysql_error());

$countries = array();

// fetch results and build multidimensional array of city counts
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
    if(isset($countries[$row['Country']][$row['State']][$row['City']])){
        $countries[$row['Country']][$row['State']][$row['City']] += 1;
    } else{
        $countries[$row['Country']][$row['State']][$row['City']] = 1;
    }
}

// loop over all countries
foreach($countries as $country => $states){
    echo $country, PHP_EOL, '{'; // output country start

    // loop over all states
    foreach($states as $state => $cities){
        echo $state, ' - '; // output state start

        $cityCounts = array();
        foreach($cities as $city => $count){
            $cityCounts[] = $city.' ('.$count.')'; // add all city counts to array
        }

        // implode all city counts and output it
        echo implode(', ', $cityCounts);

        // output new line
        echo PHP_EOL;
    }

    // output country end
    echo PHP_EOL, '}';
}
$result = mysql_query('SELECT Country, State, City From Address_Base ORDER BY Country, State, City') or die(mysql_error());

$countries = array();

// fetch results and build multidimensional array of city counts
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
    if(isset($countries[$row['Country']][$row['State']][$row['City']])){
        $countries[$row['Country']][$row['State']][$row['City']] += 1;
    } else{
        $countries[$row['Country']][$row['State']][$row['City']] = 1;
    }
}

// loop over all countries
foreach($countries as $country => $states){
    echo $country, PHP_EOL, '{'; // output country start

    // loop over all states
    foreach($states as $state => $cities){
        echo $state, ' - '; // output state start

        $cityCounts = array();
        foreach($cities as $city => $count){
            $cityCounts[] = $city.' ('.$count.')'; // add all city counts to array
        }

        // implode all city counts and output it
        echo implode(', ', $cityCounts);

        // output new line
        echo PHP_EOL;
    }

    // output country end
    echo PHP_EOL, '}';
}
浪推晚风 2024-12-10 04:16:04

SQL 查询将为您提供一组具有固定列数的结果。您的示例具有可变数量的列(多个城市计数),因此这不起作用。

您可以在 SQL 中使用 COUNT 和 GROUP BY 来获取类似的内容

Country   State    Citiescount
Canada    state1      4
Canada    state2      3
USA       state2      2

,但左侧列中会有重复项。

  SELECT country, state, COUNT(cities)
    FROM address_base
GROUP BY country, state

要消除重复项,请对其进行循环以创建一个多维数组,执行类似的操作

$countries = array();
foreach ($results as $row) {
    if (!isset($countries[$row->country])) {
        $countries[$row->country] = array();
    }
    $countries[$row->country][$row->state] = $row->citiescount;
}

或者,您可以只回显这些内容。您可以像这样一次性获取所有结果并循环整个集合,也可以将其分解为较小的查询并为每个国家或每个州执行一个查询。但请注意,将 SQL 放入循环会杀死小猫(和数据库性能):)。

SQL queries will give you a set of results with a fixed number of columns. Your example has a variable number of columns (multiple city counts) so this won't work.

You can use COUNT and GROUP BY in the SQL to get something like

Country   State    Citiescount
Canada    state1      4
Canada    state2      3
USA       state2      2

etc, but you will have duplicates in the left hand column(s).

  SELECT country, state, COUNT(cities)
    FROM address_base
GROUP BY country, state

To get rid of the duplicates, loop over it to make an multidimensional array doing something like

$countries = array();
foreach ($results as $row) {
    if (!isset($countries[$row->country])) {
        $countries[$row->country] = array();
    }
    $countries[$row->country][$row->state] = $row->citiescount;
}

Alternatively, you can just echo the stuff instead. You can either get all the results in one go like this and loop over the whole set, or you can break it into smaller queries and do one per country or one per state. Be warned, however, that putting SQL in loops kills kittens (and DB performance) :).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文