更新数量会话数组

时间:2015-02-04 19:16:17

标签: php arrays session

我需要帮助

这是我的会话数组:

Array
(
    [menu] => 
    [id] => 3
    [products] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => Produkt 1
                    [code] => 1
                    [varianta] => 
                    [pocet] => 1
                    [price] => 20
                    [pricepredtym] => 40
                )

            [1] => Array
                (
                    [id] => 2
                    [name] => Produkt 1
                    [code] => 1
                    [varianta] => 
                    [pocet] => 1
                    [price] => 20
                    [pricepredtym] => 40
                )

        )

)

我需要类似if($ _GET [id] == $ _SESSION [' products'] [id])之类的内容,并且只更改此内容" [pocet]"其中[id] = 2

$ _ GET [id] = 2;  的 $ pocet = 5;

[1] => Array
                (
                    [id] => 2
                    [name] => Produkt 1
                    [code] => 1
                    [varianta] => 
                    [pocet] => 5
                    [price] => 20
                    [pricepredtym] => 40
                )

2 个答案:

答案 0 :(得分:0)

将您的GET值与2进行比较,并将其用作SESSION数组的键。

if ($_GET['id'] == '2'){
    $_SESSION['products'][$_GET['id']]['pocet'] = '5';
}

答案 1 :(得分:0)

您可以按产品ID索引products数组。然后更新就是:

if(isset($_SESSION['products'][$prod_id])) {
    $_SESSION['products'][$prod_id]['pocet'] = $pocet;
}

否则,使用foreach循环:

foreach ($_SESSION['products'] as $i => $prod) {
    if ($prod['id'] == $prod_id) {
        $_SESSION['products'][$i]['pocet'] = $pocet;
        break;
    }
}