Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/255.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 - Fatal编程技术网

Php 递增一个关联数组键的值

Php 递增一个关联数组键的值,php,Php,请问如何增加关联数组中特定键的值 我正在做下面的工作,但似乎不起作用。 多谢各位 $_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][$qua

请问如何增加关联数组中特定键的值

我正在做下面的工作,但似乎不起作用。 多谢各位

$_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;

      }
    }
照办

$_SESSION['cart_items'][$product_id]++;
照办

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

您可以测试代码:

<?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
?>

您可以测试代码:

<?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
?>

或者您也可以执行以下操作:

或者,您也可以执行以下操作:


$\u会话[$id]++
$\u会话[$id]++
您确定没有执行任何其他操作吗$var++递增1您确定没有执行任何其他操作吗$var++增加1