$ _SESSION ['table']被POST方法var覆盖

时间:2016-10-13 23:04:39

标签: php

为什么每次使用POST方法时都会覆盖我的$ _SESSION ['table']?每当我从$ POST方法$ _SESSION ['table']获得一个新的$ mark变量时,它就被置于旧版本的位置。

<?php
session_start();

    if (!isset($_COOKIE['name'])) {
        setcookie('name', serialize($_SESSION['table']), time() + 3600 * 24);
        echo('Cookie has been made');
    }

    if (isset($_SESSION['counter'])) {
        $counter = $_SESSION['counter'];
        $_SESSION['counter'] = $_SESSION['counter'] + 1;
    }

    $_SESSION['table'] = [];

    var_dump($_SESSION['table']);

    if ('POST' === $_SERVER['REQUEST_METHOD']) {

        $mark = isset($_POST['mark']) ? trim($_POST['mark']) : NULL;
    }


    $_SESSION['table'][] = $mark;
    $_SESSION['table'][] = 3;


    var_dump($_SESSION['table']);



     function calcArithmeticMark() {
       $sum = 0;
           foreach ($_SESSION['table'] as $value) {
        $sum += $value;
              }
            $result = $sum / count($_SESSION['table']);

            return $result;
    }
    ?>

1 个答案:

答案 0 :(得分:1)

您的脚本每次都会清空会话变量:

$_SESSION['table'] = [];

如果未设置变量并且需要初始化,则应该只执行此操作:

if (!isset($_SESSION['table'])) {
    $_SESSION['table'] = [];
}