我有一个包含两列的表:多行的product_name 和product_qty
我想要输出为:
产品名称(产品数量).........
喜欢这个
产品_一(2)、产品_二(4)、产品_三(1)
我正在尝试这种方法:
require 'config.php';
$grand_total = 0;
$items = array();
$qty = array();
$allItems ='';
$stmt = $conn->prepare("SELECT * FROM cart");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
$grand_total +=$row['total_price'];
$items[] = $row['product_name'];
$qty[] = $row['qty'];
}
$array = array_combine($items, $qty);
foreach ($array as $key => $value) {
$allItems .= $key."(".$value."), ";
}
输出为: 产品一(2),产品二(4),产品三(1),
但我不想在最后加上逗号......
最佳答案
好的,答案就在您的问题标题中。 :),如下:
select concat(product_name,'(',product_qty,')') as result from my_table;
数据示例如下:
mysql> select * from my_table;
+---------------+-------------+
| product_name | product_qty |
+---------------+-------------+
| product_one | 2 |
| product_two | 4 |
| product_three | 1 |
+---------------+-------------+
3 rows in set (0.00 sec)
mysql> select concat(product_name,'(',product_qty,')') as result from my_table;
+------------------+
| result |
+------------------+
| product_one(2) |
| product_two(4) |
| product_three(1) |
+------------------+
3 rows in set (0.00 sec)
关于php - 如何在 while 循环中连接表中的两列值,如 -product_name(product_quantity), ..... 并存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56404176/