在将其添加到购物车之前,我想检查该项目是否已存在。如果项目存在,我不想两次循环显示某个项目。只需增加数组会话中现有项目的数量。
购物车中商品的会话数组:
Array
(
[0] => Array
(
[id] => 1
[qty] => 1
)
[1] => Array
(
[id] => 1
[qty] => 1
)
)
在我从购物车循环项目的页面上Cart
我有这个:
<?php
$db = require('database.php');
$cart_items = isset($_SESSION['cart']) ? $_SESSION['cart'] : null;
$products = array();
if($cart_items):
foreach ($cart_items as $key => $value)
{
$products[$key] = $value;
$id = (int) $value['id'];
$result = $db->query("SELECT * FROM products WHERE id=$id");
while($row = $result->fetch_object())
{
$products[$key]['id'] = $row->id;
$products[$key]['name'] = $row->name;
$products[$key]['price'] = number_format($row->price, 2);
// check if item exists
// this dont work i dont know how to check this
if($id == $row->id && $value['qty'] == 1)
{
$products[$key]['qty']++;
}
}
}
endif;
?>
和我循环购物车产品的正面部分:
<tbody>
<?php if($products): ?>
<?php foreach ($products as $product): ?>
<tr>
<td><?= $product['id'];?></td>
<td><?= $product['name'];?></td>
<td><?= $product['price'];?> Eur</td>
<td><input type="text" name="qty" value="<?= $product['qty']; ?>" size="5"> </td>
<td><a href="<?= SITE_URL;?>?page=cart&action=delete&id=<?= $product['id'];?>" class="btn btn-default btn-sm"> <i class="glyphicon glyphicon-remove"></i> Remove</a> </td>
</tr>
<?php endforeach; ?>
<?php endif;?>
</tbody>
所以问题是当我在 id
= 1 的项目上单击 2 次时,我会得到两个包含某些产品的新表格行。我的想法是当我在产品上单击 2 次时id = 1
只是增加购物车中现有产品的数量。
对此有什么建议吗?
首先,使用 array_column()
函数从 $products
数组中获取所有现有的产品 ID。然后检查特定项目是否存在于$products
数组中,并相应地更新产品和/或数量详细信息。
所以你的while()
循环应该是这样的:
while($row = $result->fetch_object()){
$ids = array_column($products, 'id');
if(in_array($row->id, $ids)){
$products[$key]['qty']++;
}else{
$products[$key]['id'] = $row->id;
$products[$key]['name'] = $row->name;
$products[$key]['price'] = number_format($row->price, 2);
$products[$key]['qty'] = 1;
}
}
此外,从foreach
循环中删除此语句,
$products[$key] = $value;
更新:
从OP的评论中,
现在问题在于在购物车中循环产品,通过以下方式当我在购物车中循环产品时,我有重复的产品,因为我添加一个产品 2 次并更新数量。如何防止购物车中的一件商品重复循环!如果我按 10 次乘积,id = 1。我不想要列表中的 10 个新循环项目,我只想更新数量值。防止
<tr><td> ...</td></tr> ...
中的某些项目循环
更改if
块中的代码,
$unique_ids = array_unique(array_column($cart_items, 'id'));
foreach ($cart_items as $key => $value){
if(!in_array($value['id'], $unique_ids)) continue;
$id = (int) $value['id'];
$result = $db->query("SELECT * FROM products WHERE id=$id");
while($row = $result->fetch_object()){
$ids = array_column($products, 'id');
if(in_array($row->id, $ids)){
$products[$key]['qty']++;
}else{
$products[$key]['id'] = $row->id;
$products[$key]['name'] = $row->name;
$products[$key]['price'] = number_format($row->price, 2);
$products[$key]['qty'] = 1;
}
}
$key = array_search($value['id'],$unique_ids);
unset($unique_ids[$key]);
}