2013-07-01 39 views
0

帮助!按数组排列的Codeigniter组

我正在尝试使用名为“events”的MySQL数据库表为我的CI网站生成“过去的事件”页面。有100多行数据,有些重复,涵盖5个主要国家 - 英格兰,爱尔兰,北爱尔兰,苏格兰和威尔士 - 许多不同的主要城市 - 再次包括重复条目 - 和场地。

我已经奋斗了几个星期,现在如何查询和按以下格式返回数据:

<h1>** grouped country **</h1> 
<h2> ** grouped city **</h2> 
<p>** grouped venue **</p> 

如:

<h1>England</h1> 
<h2>London</h2> 
<p>Tower of London</p> 
<h2>Manchester</h2> 
<p>Canal Street</p> 
<p>Old Trafford</p> 
<h1>Ireland</h1> 
<h2>Dublin</h2> 
<p>St. James' Gate</p> 
<h1>Scotland</h1> 
<h2>Glasgow</h2> 
<p>Buchanan Street</p> 
<p>Tron Theatre</p> 

我故意不包括任何的我的模型,视图和控制器代码,就像我迄今为止似乎混淆了人们在我看到它时试图达到的目标。而且我对我可能从错误的角度攻击这个事实开放......我只需要得出上述结果!

这感觉好像这应该是一个相当简单的事情来实现,但我需要帮助!

+1

这不仅仅是一个按国家,城市,地点排序的数据集,然后循环查看结果吗? – Strawberry

+0

类别。但它会在EVERY循环中重复国家,城市和地点,而不是在父分组变量 – user2505513

+0

之下叠加相应的信息。这正是循环的目的 - 而某些事情是x做一件事,当它发生变化时做另一件事! – Strawberry

回答

0

您需要按国家,城市和地点对结果进行排序。

当你循环,你可以做以下

<?php 
$lastCountry = null; 
$lastCity = null; 
$query = $this->db->query("SELECT country, city, venue FROM venues ORDER BY country, city, venue"); // CI query 
foreach($list = $query->result_array()) { 
    if($list['country'] != $lastCountry) { 
     $lastCountry = $list['country']; 
     print "<h1>".$list['country']."</h1>"; 
    } 
    if($list['city'] != $lastCity) { 
     $lastCity = $list['city']; 
     print "<h2>".$list['city']."</h2>"; 
    } 
    print "<p>".$list['venue']."</p>"; 
} 
+0

上面的答案不会损害视图文件的完整性吗? – user2505513

+0

妥协诚信是什么意思? 你如何输出这个取决于你。你也可以把循环放在视图中,然后把查询放在它应该是的模型中。 – Flashin

+0

但是我明白,视图文件不应该尽可能免费使用php?如果文件,公平 - 但定义变量等视图文件不是不正确的地方呢? @Flashin ps。这真的很有帮助,谢谢。 – user2505513

0

添加到闪光类的回答(和无视我的使用不赞成的方法),该程序解决方案可以是这个样子......

$query = " 
SELECT 
    * 
    FROM venues 
ORDER 
    BY country 
    , city 
    , venue; 
"; 

$lastCountry = null; 
$lastCity = null; 
$result = mysql_query($query); 
while($row = mysql_fetch_assoc($result)) { 
    if($row['country'] != $lastCountry) { 
     $lastCountry = $row['country']; 
     print "<h1>".$row['country']."</h1>"; 
    } 
    if($row['city'] != $lastCity) { 
     $lastCity = $row['city']; 
     print "<h2>".$row['city']."</h2>"; 
    } 
    print "<p>".$row['venue']."</p>"; 
}