1

首先,我的问题有点含糊或令人困惑,因为我不确定如何将我的问题表述为具体。我正在尝试查询一家针织公司的库存商数据库(使用 PHP 的学校项目),但我希望将城市打印为标题,而不是每个库存商信息。

这是我目前所拥有的:

$sql = "SELECT * FROM mc16korustockists where locale = 'south'";
    $result = pg_exec($sql);
    $nrows = pg_numrows($result);
    print $nrows;
    $items = pg_fetch_all($result);
    print_r($items);

for ($i=0; $i<$nrows2; $i++) {
    print "<h2>";
        print $items[$i]['city'];
    print "</h2>";

    print $items[$i]['name'];
    print $items[$i]['address'];
    print $items[$i]['city'];
    print $items[$i]['phone'];

    print "<br />";    
    print "<br />";

}

我正在查询数据库中的所有数据,行是参考、姓名、地址、城市和电话,并执行它。查询行数然后使用它来确定循环运行多少次迭代都很好,但我想要的是 h2 标题出现在 for ($i=0;) 行上方。

尝试只是打破我的页面,所以这可能是不可能的。我想我必须计算“城市”中的条目数,直到它检测到更改然后将标题更改为我认为的那个名称?或者进行一堆查询并为每个名称设置一个变量,但在这一点上,我不妨手动进行(我非常怀疑这是否是最佳实践)。哦,我欢迎任何对我的 PHP 的批评,因为我刚刚开始。

谢谢,如果您需要更多信息,请询问!

PS 我们的班级正在学习 PostgreSQL 而不是 MySQL,正如您在标签中看到的那样。

4

3 回答 3

1

这将解决您的问题:

$sql = "SELECT * FROM mc16korustockists where locale = 'south' order by city";

...


$city = '';

for ($i=0; $i<$nrows2; $i++) {
    if($items[$i]['city']!=$city)
    {
        print "<h2>";
            print $items[$i]['city'];
        print "</h2>";
        $city = $items[$i]['city'];
    }
    print $items[$i]['name'];
    print $items[$i]['address'];
    print $items[$i]['city'];
    print $items[$i]['phone'];

    print "<br />";    
    print "<br />";
}
于 2012-10-29T23:05:23.883 回答
0

查看上一个项目并检查它是否是同一个城市 - 如果不是,或者没有上一个项目,新城市!

于 2012-10-29T23:05:57.890 回答
0

您需要做的就是跟踪城市的变化并在变化时打印出来。

我已尝试使代码与您提供的代码尽可能相似,以便您可以看到更改发生的位置。

// store previous city, set to NULL by default so the first city from the result set will always be printed 
// (assuming that the first city from the result set is not null).

$previous_city = NULL;

for ($i=0; $i<$nrows2; $i++) {

   // determine what the city is from the current row
   // creating a separate variable for this is not really necessary, but helps to make the example clearer
   $current_city = $items[$i]['city'];

   // check if current city is different to the one in the previous row
   if ($previous_city != $current_city) {
    // city is different, lets print it
    print "<h2>";
        print $items[$i]['city'];
    print "</h2>";
    }

    print $items[$i]['name'];
    print $items[$i]['address'];
    print $items[$i]['city'];
    print $items[$i]['phone'];

    print "<br />";    
    print "<br />";

    // end of loop, the current city, now becomes the previous city
    $previous_city = $items[$i]['city'];

}

请注意,您还需要在 SQL 中 ORDER BY city 以便将 1 个城市的所有项目组合在一起,否则此方法将不起作用

于 2012-10-29T23:06:00.887 回答