【发布时间】:2017-06-26 21:07:00
【问题描述】:
我正在学习 PHP,并尝试制作一个简单的购物车/处理脚本。
我已经很好地创建了商品购物车,但是当用户承诺购买购物车中的商品时,我无法在收据中显示信息。
为了节省空间/时间,我省略了我的项目列表和购物车的生成,如果您需要,可以在 here 找到它们。
这是将数据发布到我的 checkout.php 脚本的 PHP cart.php(已更新以反映变化)
<?php
session_start(); ?>
<form name="cart" id="cart" action="checkout.php" target='_blank'
method='post'>
<h1>Your Cart:</h1>
<table>
<tr>
<td><span class='title'>ID</span></td>
<td><span class='title'>Product</span></td>
<td><span class='title'>Price</span></td>
</tr>
<?php
// Set a default total
$total = 0;
foreach ( $_SESSION['cart'] as $cartid ) {
?>
<tr>
<td width="20%">
<?php echo $cartid; ?> <input type="hidden" name="id[]"
value="<?php echo $cartid; ?>">
</td>
<td width="100%">
<?php echo $title?>
<input type="hidden" name="title[]" value="<?php echo $title; ?>">
</td>
<td width="100%">$<?php echo $price;?>
<input type="hidden" name="prices[]" value="<?php echo $price; ?>">
</td>
</tr>
<?php
$total += $price;
} // end foreach
?>
<tr>
<td>Total</td>
<td></td>
<td>$<?php echo $total; ?></td>
</tr>
</table>
<input type="submit" value="Buy" class="submit-button" />
</form>
checkout.php(已更新以反映变化)
<table>
<tr>
<th>ID</th>
<th>Product</th>
<th>Price</th>
</tr>
<?php
foreach($_POST['ids'] as $id) {
echo "
<tr>
<td>$id</td>
<td>$_POST['titles'][$id]</td>
<td>$_POST['prices'][$id]</td>
</tr>
";
}
?>
<tr>
<td>Total</td>
<td></td>
<td>$</td>
</tr>
</table>
我似乎无法让 foreach 循环读取商品 ID、标题或价格。我可以看到正在使用 print_r($_POST); 传递数组但它将每个项目索引为一个新的数组项目,例如:
Array
(
[checkout] => Array
(
[0] => A123
[1] => Item1
[2] => 1000
[3] => Z999
[4] => Item999
[5] => 9999
)
)
如何以更有意义的方式发布信息,即关联数组。然后使用该关联数组以表格格式显示信息?
预期输出
<table>
<tr>
<th>ID</th>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>A123</td>
<td>Item1</td>
<td>$1000</td>
</tr>
<tr>
<td>Z999</td>
<td>Item999</td>
<td>$9999</td>
</tr>
<tr>
<td>Total</td>
<td></td>
<td>$10999</td>
</tr>
</table>
注意:这只是一个学习练习,因此不需要对数组进行清理,也不需要 SQL。
编辑:更新以反映@Obsidian Age 建议,现在出现解析错误
【问题讨论】:
-
您必须根据 ID 从某处获取价格和标题...