数组编辑无法正常工作


Array editing not working correctly

好的,这是我编辑数组中特定条目的代码,数组布局如下。

$counter = 0;
foreach($_SESSION['cart'] as $listitem){
    if ($listitem[0] == $_POST['product']){
        if ($listitem[1] <= $_POST['remove']){
            $remove = array($listitem[0], 0);
            $_SESSION['cart'][$counter] = $remove;
        } else {
            $result = $listitem[1] - $_POST['remove'];
            $remove = array($listitem[0], $result);
            $_SESSION['cart'][$counter] = $remove;
        }
    }
$counter = $counter++;
}

这是我的$_SESSION['Cart']阵列布局

Array( 

 - [0] => Array ( [0] => 8 [1] => 0 )
 - [1] => Array ( [0] => 10 [1] => 0 )       
 - [2] => Array ( [0] => 8 [1] => 1 )
)

要么我对数组的理解是错误的,这行代码是错误的:

$_SESSION['cart'][$counter]

否则我的计数器将不计算在内:

$counter = $counter++;

由于唯一的值它不断编辑第一个条目 [0]

谁能看出我哪里出错了?

$counter = $counter++什么都不做。

$counter++ 递增 $counter 的值,但计算结果为其当前值(递增前的值)。这样,您就可以将$counter设置为具有自身的价值,而这通常不会起到太大作用。

只需$counter++即可。

(附加信息:还有预增量运算符 ++$counter ,它递增变量并返回值。

$counter = $counter++ 会将$counter设置为其当前值,然后将其递增 1。 这是一个多余的陈述。 如果您确实打算将变量$counter增加 1,则只需使用 $counter++。