检查产品是否存在于会话数组中,如果存在,则使用php增加该产品的计数值

时间:2013-11-27 05:54:08

标签: php arrays session

我将产品作为数组添加到会话中,但在将该产品添加到会话之前,如何检查会话数组中是否存在该产品。 如果产品存在,我想增加该产品的数量,如果没有将该产品添加到会话数组。我的PHP代码如下所示。

session_start(); 
if(empty( $_SESSION['fields1'] )) {
  $_SESSION['fields1'] = array();
}    
$qty = 1;

$id = $_POST['id'];
$name = $_POST['name']; 
$description = $_POST['description'];
$cnt = 0;
print_r($_SESSION['fields1']);
if (! empty($_SESSION['fields1'])){
    foreach ($_SESSION['fields1'] as $key=>$val){
            if ($id == $val['id']){
                 $qty = $val['qty']++;
                 //echo "qty ===".$qty;
                 $_SESSION['fields1'][$cnt]['qty'] =  $val['qty']++;                     
            }
            else
            {
                $arrayval =  array('id' => $id,'name' => $name,'description' => $description,'qty' => $qty);
                array_push($_SESSION['fields1'] ,$arrayval );
            }
            $cnt++;
    }

}else{
    $arrayval =  array('id' => $id,'name' => $name,'description' => $description,'qty' => $qty);
    array_push($_SESSION['fields1'] ,$arrayval );
}
//print_r($_SESSION['fields1']);
echo json_encode($_SESSION['fields1']); 

1 个答案:

答案 0 :(得分:0)

如果$id是产品ID且fields是产品数组,请尝试以下操作:

if(empty($_SESSION['fields'][$id]))
    $_SESSION['fields'][$id]['qty'] = 1;
else
    $_SESSION['fields'][$id]['qty']++;