php多会话阵列更新

时间:2014-05-12 23:48:14

标签: php arrays session

我想更新产品库存会很高兴,如果你帮助我不能。 我的产品清单数组

$_SESSION['item'];
Array ( 
[0] => Array ( [product_id] => 9 [stock] => 20 ) 
[1] => Array ( [product_id] => 8 [stock] => 30 ) 
[2] => Array ( [product_id] => 7 [stock] => 26 ) 
[3] => Array ( [product_id] => 6 [stock] => 42 ) 
)

我做

$product_id = mysql_real_escape_string($_POST['product_id']);
$stock  = mysql_real_escape_string($_POST['stock']);
$found = false;
foreach($_SESSION['item'] as $product){
    if($product_id == $product['product_id']) {
        $found = true;
        break;
    }
}

if($found){
    $_SESSION['item'][$product_id]['stock'] += $stock;
}else{

    // go get new product and add to $_SESSION['item']
}

1 个答案:

答案 0 :(得分:1)

试试这个:

$product_id = mysql_real_escape_string($_POST['product_id']);
$stock  = mysql_real_escape_string($_POST['stock']);
$found = false;
foreach($_SESSION['item'] as $index => $product){
    if($product_id == $product['product_id']) {
        $found = true;
        break;
    }
}

if($found){
    $_SESSION['item'][$index]['stock'] += $stock;
}else{
    // go get new product and add to $_SESSION['item']
}

说明:$_SESSION['item']数组未被product_id 编入索引。因此,您必须在foreach循环中获取并存储当前数组项的索引,并使用它来更新$_SESSION['item']数组。