Php 防止将重复ID添加到会话(阵列)

Php 防止将重复ID添加到会话(阵列),php,mysql,arrays,Php,Mysql,Arrays,我得到了一个将id添加到数组的会话,问题是即使id已经存在,也会添加每个id。如何防止将重复id添加到阵列中 我想我需要检查数组中使用的id,但我不知道如何正确使用它 我使用以下链接将产品id发送到我的报价页: <p><a class="offertelink" href="offerte.php?product='.$productcr[0]['id'].'">Request a quote</a></p> 最后,加载阵列中具有ID的所有产品:

我得到了一个将id添加到数组的会话,问题是即使id已经存在,也会添加每个id。如何防止将重复id添加到阵列中

我想我需要检查数组中使用的id,但我不知道如何正确使用它

我使用以下链接将产品id发送到我的报价页:

<p><a class="offertelink" href="offerte.php?product='.$productcr[0]['id'].'">Request a quote</a></p>
最后,加载阵列中具有ID的所有产品:

if(count($_SESSION['product'])  != 0){
//  offerte overzicht
$offerte            = "SELECT * FROM `snm_content` WHERE `id` in (".$conn->real_escape_string($prods).")  AND state = 1";
$offertecon         = $conn->query($offerte);
$offertecr          = array();
while ($offertecr[] = $offertecon->fetch_array());
}
但现在每次我重新加载页面时,都会再次添加id,这并不是很糟糕,因为产品只加载一次,但我仍然想解决这个问题,因为我认为查询检查大量重复id不是最好的方法。

选项1 在数组()中使用
以防止重复:

// CHECK FIRST THAT $_GET['product'] IS SET BEFORE ADDING IT TO SESSION
if( isset($_GET['product'])){
    if(!in_array($_GET['product'], $_SESSION['product']){
        // product not exists in array
        $_SESSION['product'][] = $_GET['product'];
    }
}
选项2添加产品前清空数组

//if(!isset($_SESSION['product'])){
    $_SESSION['product'] = array();
//}

在数组中使用
很简单-您只需检查
元素是否在数组中

var_dump(in_array($element, $array));
就你而言,它是:

var_dump(in_array($_GET['product'], $_SESSION['product']));
支票是:

// i advise you to check product value as `int`.  
// Because values as `empty string` or `0` or `false` are considered set
if( 0 < intval($_GET['product']) && !in_array($_GET['product'], $_SESSION['product']) ) {
    $_SESSION['product'][] = $_GET['product'];
}
在这种情况下,您甚至不需要检查您的密钥是否存在-如果存在,它将被覆盖,如果不存在-将被添加:

if( 0 < intval($_GET['product']) ) {
    $_SESSION['product'][ $_GET['product'] ] = 1;
}
// but here you need to take array keys instead of values
$prods  = implode(",", array_keys($_SESSION['product']));
if(0
如果…@Dave这正是我在问题中所说的,我想我必须使用它,但不知道如何使用它。如何在数组中使用
?@u\u mulder不知道如何在变量中使用它,但我修复了它。你推荐什么?回答我自己的问题或删除它。
$_SESSION['product'] = [
    '101' => 1,
    '102' => 1,
    '106' => 1,
];
if( 0 < intval($_GET['product']) ) {
    $_SESSION['product'][ $_GET['product'] ] = 1;
}
// but here you need to take array keys instead of values
$prods  = implode(",", array_keys($_SESSION['product']));