gpt4 book ai didi

php - 在 MySQL 中连接数据

转载 作者:行者123 更新时间:2023-11-29 04:40:36 24 4
gpt4 key购买 nike

我的数据库中有以下数据:

initial   |    word
---------------------------
E | Example1
E | Example2
N | Nextexample1

期望的输出:

E : Example1, Example2
N : Nextexample1

因此对于每个首字母,它应该显示所有以该首字母开头的单词。

此时输出:

E : Example1
E : Example2
N : Nextexample1

此时我的代码:

<?php
$pdo = new PDO('mysql:host=...');
$sql = "SELECT DISTINCT initial, word FROM `exampletable` ORDER by initial ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute();

if($stmtrecords = $stmt->fetchall(PDO::FETCH_ASSOC))
{

foreach($stmtrecords as $result)
{
?>

<?php echo $result['initial'];?> : <?php echo $result['word'];?>

问题:

我完全理解为什么我得到错误的输出但不知道如何解决它。我想我需要像 foreach 循环中的 foreach 循环来获得正确的输出,但如何将单词链接到正确的首字母?

最佳答案

您可以使用单个 SQL 查询来完成此操作。

SELECT `initial`, GROUP_CONCAT(`word` SEPARATOR ', ') as `output` 
FROM `table` GROUP BY `initial` ORDER BY `initial` ASC

在此查询中,您要求 MySQLinitial 对记录进行分组,并且您使用 GROUP_CONCAT()函数将每个分组聚合成一个单独的行。

使用示例数据

initial | word
--------+--------------
E | Example1
E | Example2
Z | Zebra
N | NextExample
O | OtherExample
O | OtherExample2

会返回:

initial | output
--------+--------------
E | Example1, Example2
N | NextExample
O | OtherExample, OtherExample2
Z | Zebra

关于php - 在 MySQL 中连接数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29857133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com