2015-03-13 113 views
1

好吧,這裏是我的代碼來編輯數組中的特定條目,並且數組佈局如下。數組編輯無法正常工作

$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]

任何人都可以看到我出錯的地方嗎?

+0

將'$ counter = $ counter ++'改爲'$ counter ++'或'$ counter = $ counter + 1'或'$ counter + = 1'或'++ $ counter'等。 – Jonathon 2015-03-13 13:31:11

+0

請閱讀[increment and遞減運算符](http://php.net/manual/en/language.operators.increment.php)。 – 2015-03-13 13:32:29

+0

感謝所有的答案,白癡新手的錯誤,有一件事一直困擾我超過一個小時.. – PirateScott 2015-03-13 13:42:10

回答

2

$counter = $counter++什麼都不會做。

$counter++增量$counter價值,但評估它的當前值(一個是增量前有)。這樣,你就可以設置$counter來擁有自己的價值,而這通常不會有太大的作用。

只需改爲$counter++

(附加信息:也有在預先遞增運算符,++$counter,這增加變量,並返回值。)

+0

它有一個$計數器= 0;如果這不適用,那麼在foreach之上? – PirateScott 2015-03-13 13:31:50

+0

當您執行'$ counter ++'時,它會將$ counter增加1,但它會在它被更改之前返回它**的值,所以基本上,您正在執行'$ counter = $ counter'或'$ counter = 0' – Jonathon 2015-03-13 13:33:03

+0

啊,我看到我現在做錯了什麼...非常感謝:P – PirateScott 2015-03-13 13:33:07

0

$計數器= $計數器++將計數器設置$其當前值,然後增加一個。這是一個多餘的陳述。如果你打算只是將變量$ counter加1,那麼就使用$ counter ++。