2012-10-29 92 views
1

首先,我的问题有点模糊或混乱,因为我不确定如何将我的问题描述为具体。我试图查询一家Knitting公司的库存商数据库(使用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,因为我刚刚开始。

谢谢你,如果你需要更多的信息,只要问问!

P.S.我们的班级正在使用PostgreSQL而不是MySQL学习,正如您在标签中看到的一样。

+0

很高兴地看到用PostgreSQL教学的人。作为结果,你将会学习更少的坏习惯。尽管如此,请在问题中提及您的PostgreSQL版本。 –

回答

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 />"; 
} 
+0

谢谢!完美的作品。我非常感谢你的帮助。 – Sentry

+1

如果答案是正确的,请标记为,否则stackoverflow将永远不会知道您的问题已得到解决。考虑一些有用的投票答案。这有助于其他有类似问题的用户更轻松地找到答案 –

0

看看以前的项目,并检查它是否是同一个城市 - 如果不是,也没有以前的项目,新的城市!

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,使所有从1个城市的项目组合在一起,否则此方法将无法正常工作