PHP:创建动态变量字符串

时间:2015-06-28 21:53:12

标签: php shopping-cart dynamic-variables

我需要为购物车创建动态变量以发送到支付网关。

每个变量的格式为:

$parameters['Product Name: Qty = '. $cart_qty] = $subtotal;

因此,如果我订购两个产品,参数列表将是:

$parameters['Product1: Qty = 2'] = 24.00;

$parameters['Product2: Qty = 3'] = 60.00;

......等等。

如何通过循环遍历每个产品将这些参数生成为字符串?

如:

while ($data_cart = mysql_fetch_array($result_cart)) {
    $prodName = $data_product['prodName'];
    $unitPrice = number_format((float)$data_product['priceRetail'], 2, '.', '');
    $cart_qty = $data_cart['qty'];
    $subtotal = $cart_qty * $unitPrice;

    $parameter .= ??? // <-- How to create a dynamic string here to output later

}

然后我将如何将其写入页面,回显或打印?

1 个答案:

答案 0 :(得分:0)

在构建完整数组之后尝试使用像http_build_query()这样的查询构建函数(根据您的示例,您的密钥有引号问题)

<?php
$parameters['Product1: Qty = 1'] = '24.00';
$parameters['Product3: Qty = 3'] = '24.00';
$parameters['Product2: Qty = 5'] = '24.00';
$parameters['Product5: Qty = 1'] = '24.00';

echo http_build_query($parameters);
?>

给你:

Product1%3A+Qty+%3D+1=24.00&Product3%3A+Qty+%3D+3=24.00&Product2%3A+Qty+%3D+5=24.00&Product5%3A+Qty+%3D+1=24.00