php - 基于不同键的回显数组

标签 php mysql arrays database key-value

我已经“排序”了一个数据库,使其按国家/地区升序排列,然后按年份降序排列。每个数据库记录包含:国家名称、年份、详细信息。有很多重复的国家,但年份不同。例如:

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/

相关文章:

php - 在不重复函数调用和创建额外变量的情况下找到第一个匹配项。有可能吗?

php - 在 MySQL 表中查找用户名的唯一 IP 地址

mysql - Xampp 控制面板 mysql 无法启动

php - 尝试在 Amazon AWS 上的 mySQL 数据库上使用 JSON_OBJECT 函数

javascript - 我们可以从提交表单中发布 getelement.id ('' ).innerhtml 吗?

c - 如何从指针变量计算数组的大小?

ios - 如何将数字数组减少为具有给定长度且信息丢失少的数组

iOS UITextViews 数据挥之不去,即使我清除了一个数组

mysql - 如何更新MySql列

php - 在 mysql 中为用户获取每场比赛的前 3 名结果