duanbo6871 2015-04-06 19:18
浏览 35
已采纳

php从数组打印更多结果并将它们分组

I have one problem which I couldn't resolve.

Let's say that I have a table in mysql like this:

 id |  name   |  city
 ---|---------|---------
 1  |  En     |  Madrid
 2  |  Nicole |  Paris
 3  |  Robin  |  London
 4  |  Wayne  |  Paris
 5  |  John   |  Madrid
 6  |  Frank  |  Madrid

I wanna list all name of one city in one div, I wanna do that for all cities.

Examples:

En, John, Frank
Nicole, Wayne
Robin

All those rows to be in div, one below to another. In this particular case result is 3 div. I have managed only write every name in particular div, 6 of them. I did that in this way:

$result = mysql_query("SELECT * FROM table_name");
$count=mysql_num_rows($result);    
$i=0;
for($i=0;$i<=$count-1;$i++)
  {            
    $row=mysql_fetch_array( $result );    
    echo "<div>$row[name]</div>";        
  }  

Can anyone helps me?

  • 写回答

1条回答 默认 最新

  • donglaohua1671 2015-04-06 19:39
    关注

    Solution 1

    $result = mysql_query("SELECT * FROM table_name ORDER BY city");
    $count=mysql_num_rows($result);
    
    $i=0;
    $city = '';
    for($i=0;$i<=$count-1;$i++) { 
    
        $row=mysql_fetch_array( $result );
        if ($city == '' ) {
           echo "<div>";    
        } elseif ($city<>$row['city']) {
           echo "</div><div>";  
        }  
        $city = $row['city']
        echo $row['name'].' &nbsp';
    } 
    
    if ($city<>'') echo '</div>';
    

    Solution 2

    $result = mysql_query("SELECT GROUP_CONCAT(name) as name_list, city FROM table_name GROUP BY city");
    $count=mysql_num_rows($result);
    $i=0;
    $city = '';
    for($i=0;$i<=$count-1;$i++) { 
    
        $row=mysql_fetch_array( $result );
        echo '<div>'.$row['name_list'].'</div>';
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效