Php 如何连接两列值,如-产品名称(产品数量)。。。。。从while循环中的表,并存储在变量中

Php 如何连接两列值,如-产品名称(产品数量)。。。。。从while循环中的表,并存储在变量中,php,mysql,function,Php,Mysql,Function,我有一个表,有两列:product\u name和product\u Quantity,有多行 我希望输出为: 产品名称(产品数量) 像这个 产品一(2)、产品二(4)、产品三(1) 我正在用这种方法尝试: require 'config.php'; $grand_total = 0; $items = array(); $qty = array(); $allItems =''; $stmt = $conn->prepare("SELECT * FROM cart"); $stmt-&g

我有一个表,有两列:product\u name和product\u Quantity,有多行

我希望输出为:

产品名称(产品数量)

像这个

产品一(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)

但我不希望逗号出现在最后……

您可以使用函数

表格

无需使用foreach和array\u组合all。从查询本身,您可以根据需要获取数据。检查下面的更新代码

$grand_total = 0;
$sqlStmt = "SELECT CONCAT(product_name, '(', product_qty,')') AS ItemQty,total_price FROM cart";
$stmt = $conn->prepare($sqlStmt);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
    $grand_total +=$row['total_price'];
    $items[] = $row['ItemQty'];
}
echo "<pre>";
print_r($items);
print_r($grand_total);

好的,答案在你的问题标题中。:),如下:

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的任何数组函数来实现这一点吗?当然,我们可以,您只需
选择
产品名称和产品数量列,然后使用php提供的连接字符串方法将结果连接到
产品名称(产品数量)
格式。我不熟悉php,但是php的字符串连接函数必须很简单。@Wolfmania没有必要
foreach
array\u combine
现在检查我更新的答案
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)