我正在尝试从查询字符串中获取值并将它们添加到数组内的数组中。输出查询字符串类似于:
add_to_cart.php?product_id=4&product_name=Pizza&quantity=1&additional_id[]=1&additional_quantity[]=3&additional_id[]=4&additional_quantity[]=5
我在查询字符串中显示每个additional_id
和additional_quantity
变量,并带有以下代码。我将每个additional_id
与我在数据库表附加中的ID进行比较,并将all插入到数组中。我的文件 add_to_cart.php 文件中存在以下代码:
if(isset($_SESSION['cart']))
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns = array
(
'product_id_session' => $product_id_session,
'product_id' => $product_id,
'product_name' => $product_name,
'product_price' => $product_price,
'quantity' => $quantity,
'additionals' => array()
);
if(isset($_GET['additional_id']) && $_GET['additional_id'] != "")
{
foreach($_GET['additional_id'] as $additional => $value)
{
$additional_id = $value;
if(isset($_GET['additional_quantity'][$additional]))
{
$additional_quantity = $_GET['additional_quantity'][$additional];
if($additional_quantity <= 0 || $additional_quantity > 5)
{
$additional_quantity = null;
}
else
{
$sql2 = "SELECT additional_id, additional_name, additional_price FROM additionals WHERE additional_id LIKE '{$additional_id}'";
$stmt2 = $connection->prepare($sql2);
$stmt2->execute();
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns['additionals'][]['additional_id'] = $additional_id;
$columns['additionals'][]['additional_name'] = $additional_name;
$columns['additionals'][]['additional_price'] = $additional_price;
$columns['additionals'][]['additional_quantity'] = $additional_quantity;
}
}
}
}
}
$_SESSION['cart'][$product_id_session] = $columns;
}
header('Location: products.php?action=added&product_name=' . $product_name);
}
在cart
会话中添加所有内容后,在 cart.php 页面中,我正在尝试使用所选的附加内容和数量来展示产品:
foreach($_SESSION['cart'] as $product)
{
echo "<tr>";
echo "<td>{$product['product_name']}</td>";
echo "<td>${$product['product_price']}</td>";
echo "<td>{$product['quantity']}</td>";
echo "<td>";
foreach($product['additionals'] as $additional)
{
echo "<p>{$additional['additional_quantity']}x{$additional['additional_name']} - {$additional['additional_price']}</p>";
}
echo "</td>";
echo "</tr>";
}
但是我做错了,我认为这两个代码不能正常工作
我的输出很尴尬,就像这样:
我是以正确的方式做到的吗?也许我没有使用foreach
正确循环,或者附加功能没有成功添加?对不起,我以前从未使用过多维数组。有办法做我想做的事吗?谢谢!
答案 0 :(得分:1)
根据评论的解决方案 -
您的问题是由$columns['additionals'][]
引起的,因为它导致每个值都被添加为自己的数组。这是通过添加$additional
作为数组键 -
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns['additionals'][$additional]['additional_id'] = $additional_id;
$columns['additionals'][$additional]['additional_name'] = $additional_name;
$columns['additionals'][$additional]['additional_price'] = $additional_price;
$columns['additionals'][$additional]['additional_quantity'] = $additional_quantity;
}
或者你也可以 -
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns['additionals'][] = array('additional_id' => $additional_id,
'additional_name' => $additional_name,
'additional_price' => $additional_price,
'additional_quantity' => $additional_quantity);
}