php - 合并两个 mysql 结果

标签 php mysql html-table

情况是这样的..

while($row = mysql_fetch_assoc($sql)){

$name = $row['name'];
$class = $row['class'];
$result = $row['phone'];

$data .= '<td>'.$name.'</td><td>'.$class.'</td><td>'.$result.'</td>';
}



echo "<table><tr>'.$data.'</tr><table>"

$name$class 将出现一次,但 $result 将出现多次。我想将它们一起显示在单个 html 行中..像这样

Kevin | IX | 5343634,3565656
Melvin | X | 54534,3778,54434

最佳答案

一种可能的方法:首先将结果收集在关联数组中,按名称索引*因为它们似乎是唯一的),然后对这些结果执行任何您想要的操作。例如:

$results = array();
while ($row = mysql_fetch_assoc($sql)) {
  $name = $row['name'];
  $results[$name]['class'] = $row['class'];
  $results[$name]['phone'][] = $row['phone'];
}

echo '<table>';
foreach ($results as $name => $result) {
  echo '<tr><td>' . $name . '</td><td>' . $result['class'] 
          . '</td><td>' . implode(',', $result['phone']) . '</td></tr>';
}
echo '</table>';

另一种方法:让您的查询使用 GROUP BY 和 CONCAT_WS 聚合电话本身

  SELECT name, class, CONCAT_WS(',', phone) AS phones
    FROM students
GROUP BY name 

然后,您将获得已以逗号分隔格式提供给您的给定名称的所有电话。

<小时/>

作为旁注,请考虑切换到 mysqlipdo 扩展 - 而不是 mysql。这就是PHP documentation对此说道:

This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used.

这并不像听起来那么简单,但仅对于准备好的语句而言,这绝对值得付出努力。

关于php - 合并两个 mysql 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22880982/

相关文章:

php - 我想从 MySQL 数据库中随机选择一个 YouTube 视频,并将其显示在我的网页上

c# - 使用 C# 和查询选择特定条件,将查询拉出的数字( double )相乘

html - 如何在 css 中为两个相邻单元格设置单个边框

php - 未找到对象!在此服务器上找不到请求的 URL

php - 学说 2 dql 别名

php - 第 275 行用户 Sugar/modules/Accounts/Account.php 的访问被拒绝

html - html表格内的自动滚动文本

html - 重新排列移动表格中单元格的顺序

php - 使用复选框从数据库表中删除一行

javascript - Fullcalendar - 在数据库中保存事件