簡體   English   中英

結合兩個mysql結果

[英]Combine two mysql results

就是這種情況

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

一種可能的方法:首先將結果收集到一個關聯數組中,並按name索引(因為它們看起來是唯一的)(然后似乎是唯一的),然后對這些結果執行任何您想要的操作。 例如:

$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文檔所說的:

自PHP 5.5.0起不推薦使用該擴展,不建議編寫新代碼, 因為將來會刪除該擴展。 相反,應使用mysqliPDO_MySQL擴展名。

這聽起來並不簡單,但僅針對准備好的語句,絕對值得付出努力。

以下將顯示一個TD,其逗號分隔。

$result = array();

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

array_push($result, $row['id']);
}



echo "<table><tr><td>". implode(',',$result) ."</td></tr><table>"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM