我已经“排序”了一个数据库,使其按国家/地区升序排列,然后按年份降序排列。每个数据库记录包含:国家名称、年份、详细信息。有很多重复的国家,但年份不同。例如:
Albania, 2000, details
Albania, 1965, details
Croatia, 2014, details
Croatia, 2003, details
无法弄清楚如何回显数组以获得如下所示的结果,其中国家/地区位于一行,年份和详细信息列在下面,但没有重复国家/地区的名称:
Albania
2000, details
1965, details
Croatia
2014, details
2003, details
似乎我需要每个不同的国家、年份和详细信息?
到目前为止,这是我的 php:
$result = mysql_query("SELECT country, year, details FROM studies ORDER BY country, year DESC ");
//output data from each row in db
while($row = mysql_fetch_array($result)) {
echo " Country: " .$row['country']. "<br /> Year: " .$row['year']. " Details: ".$row['details']. "<br /><br /> ";
}
非常感谢任何帮助,我很难过!
最佳答案
尝试添加国家/地区检查:
$newcountry = '';
while($row = mysql_fetch_array($result)) {
if ($newcountry != $row['country']) {
echo "Country:". $row['country']."<br />";
$newcountry = $row['country'];
}
echo " Year: " .$row['year']. " Details: ".$row['details']. "<br /><br /> ";
}
这应该可行,因为您已按国家/地区对查询进行排序。这很关键,否则你绝对应该添加 GROUP BY
子句添加到您的 SQL。
编辑: 添加 <div>
在该组中,您只需更改 echo 顺序,首先检查该国家/地区是否已设置一次。它看起来像:
$newcountry = 'undefined';
while($row = mysql_fetch_array($result)) {
if ($newcountry !='undefined' && $newcountry != $row['country']){
echo '</div>'; // only add a closing div if a new country (and not 1st)
}
if ($newcountry != $row['country']) {
echo "Country:". $row['country']."<br /><div class='countryDetail'>";
$newcountry = $row['country'];
}// added the start of the <div>
echo " Year: " .$row['year']. " Details: ".$row['details']. "<br /><br /> ";
}
if ($newcountry != 'undefined') { //make sure at least one <div> is set
echo "</div>"; // close the last <div>
}
我添加了类 countryDetail
到 div,所以你可以将它与 toggle
一起使用在你的 jQuery 中。
关于php - 基于不同键的回显数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28465213/