如何在单个foreach循环php中比较值


How to compare values in a single foreach loop php

我正在开发opencart。我不想允许用户在购物车中多次添加相同的产品。为此,我有一个逻辑,我想比较购物车中的产品。我会得到每个产品的产品id(用户通过点击添加到购物车添加了多少),然后我会比较这些id。如果它们是一样的,我会给它们显示错误消息,否则它们可以继续。对于这个逻辑,我一直使用这个代码到现在。

$products = $this->cart->getProducts();
foreach ($products as $product) 
{
$p_id=$product['product_id'];   
}

但我不明白,我将如何比较foreach循环中的两个产品ID。然后添加我的逻辑,即如果产品ID相等,则显示错误消息。

您只需在用户将产品添加到购物车时进行检查即可。为此,修改controller->checkout->cart.php 中的add功能

public function add() {

添加

$products = $this->cart->getProducts();
if($products){
 foreach ($products as $product) 
    {
        if($this->request->post['product_id'] == $product['product_id']){
            $json['error']['blabla'] = 'Your warning message.';
            break;
        }
    }
}

之前

if (!$json) {

并在您想要显示的任何位置显示该错误。就是这样。

您可以获得新产品id的值,然后像一样进行比较

//get product id to be added
$new_product = "get ID";
$products = $this->cart->getProducts();
foreach ($products as $product) 
{
$p_id=$product['product_id']; 
//compare with new product_id with existing
if ($_pid == $new_product){
echo " Product already exists!!";
}
}
$products = $this->cart->getProducts();
$exist = false;
foreach ($products as $product) 
{
if ($p_id == $product['product_id']) {
$exist = true;
break;
}   
}
if (!$exist) {
//add product co cart
}

尝试这种方式

$products = $this->cart->getProducts();
$p_id = '';
foreach ($products as $product) 
{
  if($p_id != $product['product_id']) {
    $p_id=$product['product_id'];
  }else{
    echo " Product already exists!!";
  }
}

这将为您提供一个唯一的ID列表和一个需要删除的ID列表,以使列表唯一。

    // get the list of ID's
    $products = $this->cart->getProducts();
    $all = array();
    foreach ($products as $product) 
    {
        $all[] = $product['product_id'];   
    }
    // Flip the array twice to just get the unique ID's
    $unique = array_flip(array_flip($all));
    // Get a list of ID's that were lost
    $difference = array_diff_assoc($all, $unique);