PHP实现SQL多表关联查询结果的个性化格式化输出问题
问题解决:PHP实现按用户ID分组格式化输出产品信息
问题背景
用户拥有Customer和Product两张SQL数据表,已通过PHP实现两表关联查询并获取数据,但无法按需求格式化输出消息:单个产品时输出“Your Id is XXX the product is XXX.”,多个产品时输出“Your Id is XXX the products are XXX and XXX.”。
数据表结构
Customer表
| ID | product id |
|---|---|
| 01 | 202201 |
| 02 | 202103 |
| 03 | 202204 |
| 03 | 202204 |
Product表
| product id | product |
|---|---|
| 202201 | phone. |
| 202103 | monitor. |
| 202204 | laptop. |
| 202204 | desktop. |
SQL查询结果
| ID | product |
|---|---|
| 01 | phone |
| 02 | monitor |
| 03 | laptop |
| 03 | desktop |
当前与期望输出
当前PHP输出
01 - phone 02 - monitor 03 - laptop, desktop
期望PHP输出
Your Id is 01 the product is phone. Your Id is 02 the product is monitor. Your Id is 03 the products are laptop and desktop.
现有代码问题分析
原代码存在多个核心问题:
- 使用中文引号“”作为数组索引,PHP无法识别,需替换为英文引号""
- 逻辑混乱:在while循环中错误判断产品数量,未按用户ID分组存储产品
- 变量
$i未定义就使用,导致条件判断完全失效 - 多产品拼接仅用逗号分隔,不符合需求中“and”连接的格式要求
修正后的代码
<?php // 规范SQL关联查询写法 $sql = "SELECT a.id, b.product FROM customer a JOIN product b ON a.`product id` = b.`product id`"; $result = mysqli_query($conn, $sql); // 按用户ID分组存储对应产品 $customerProducts = []; while ($row = $result->fetch_assoc()) { $id = $row['id']; $product = trim($row['product']); // 去除产品名末尾的句号 $customerProducts[$id][] = $product; } // 遍历分组数据,生成格式化输出 foreach ($customerProducts as $id => $products) { $productCount = count($products); if ($productCount === 1) { echo "Your Id is {$id} the product is {$products[0]}.\n"; } else { // 处理多产品格式:最后一个用and连接 $lastProduct = array_pop($products); $productList = implode(', ', $products) . ' and ' . $lastProduct; echo "Your Id is {$id} the products are {$productList}.\n"; } } ?>
代码说明
- 分组存储:用
$customerProducts数组以用户ID为键,存储该用户的所有产品,解决原代码未分组的核心问题 - 格式处理:通过
trim()去除产品名末尾的句号,保证输出内容整洁 - 多产品拼接:弹出最后一个产品,前面产品用逗号分隔,最后用“and”连接,完全匹配需求格式
- SQL规范:使用
JOIN ON替代隐式关联,代码可读性更高
内容的提问来源于stack exchange,提问作者Naveen
相关产品推荐
相关产品推荐

