Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php多会话数组更新_Php_Arrays_Session - Fatal编程技术网

php多会话数组更新

php多会话数组更新,php,arrays,session,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] => Ar

我想更新产品库存,如果你能帮我,我会很高兴的。 我的产品列表数组

$_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 $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']
}

说明:
$\u会话['item']
数组未按
产品id编制索引。因此,您必须在foreach循环中获取并存储当前数组项的索引,并使用它更新
$\u会话['item']
数组。

那么问题是什么?哪里有错误?什么不起作用?foreach循环后,
$found
的值是多少?不更新产品库存它不起作用,
stock
不是
product\u id
的键,我将使用product\u id作为第一级键来重构数组
$\u会话['item']
不按产品id索引!太好了,我很高兴:)作为奖励,你们可以投票支持我的答案,并将其标记为答案。谢谢。分数是多少:)我向上掷箭头说15个人需要更多
$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']
}