2016-06-16 4 views
0

연관 배열에서 특정 키의 값을 어떻게 증가 시킵니까?하나의 연관 배열 키 값 증가

아래 작업을 수행하지만 작동하지 않는 것 같습니다. 감사합니다.

$_SESSION['cart_items'] = ["a" => 1, "b" => 1]; 
$product_id can be a or b. 
    foreach ($_SESSION['cart_items'] AS $id => $quantity){ 
     if ($id == $product_id){ 
     $_SESSION[$product_id][$quantity] +=1; 

     } 
    } 
+0

'$ _SESSION [$ 아이디] + +' – zerkms

답변

1

그럼 당신이 코드를 테스트 할 수 있습니다 수행

<?php 

// start the session and avoid notice 
@session_start(); 

// if not set session for cart_items, set first 
if (! isset($_SESSION['cart_items'])) { 
    // this is session data with product details 
    $_SESSION['cart_items'] = array("a" => 1, "b" => 1); 
} 

// assuming if product is 'a' 
$product_id = $_GET['product_name']; 

// check if product 'a' exist in SESSION as KEY then add +1 

if (isset($_SESSION['cart_items'][$product_id])) { 
    $_SESSION['cart_items'][$product_id]++; 
} 

// debug value of SESSION 
echo '<pre>', print_r($_SESSION, true), '</pre>'; 


// run this code after save in file e.g. test.php?product_name=a or text.php?product_name=b 
?> 
2

그냥

$_SESSION['cart_items'][$product_id]++; 
+0

작동하지 않습니다. 값은 2 씩 증가합니다. – radioactive

+0

다른 것을 실행하지 않습니까? $ var ++는 1 씩 증가합니다 – Pipe

+0

예. 그것은 효과가 있었다. 실수는 내 것이 었습니다. – radioactive

0

을 아니면도 수행 할 수 있습니다

$_SESSION[$product_id] = parseInt($quantity) + 1;