未定义的索引 (Cookie)

Undefined index (Cookie)

我对 PHP 和他的 Cookie 有疑问。 我正在用 cookie 做一个数组。

$possition = 0
setcookie('array['.$possition.']', "test");

echo $_COOKIE['array['.$possition.']'];

使用此代码,我创建了一个名为 'array[0]' 且值为 'test' 的 Cookie(我可以在 Google Chrome cookie 管理上看到它。)

但是,当我使用 'echo' 时出现此消息:

Notice: Undefined index: array[0] in C:\xampp\htdocs\recub.php on line 7

但是这个 cookie 不是空的...

有人知道怎么解决吗?我已经用 "isset" 试过了,但是这个什么也没有显示。

此致

更新:

使用 Rizier123 可以延迟工作...这是我的完整代码:

index.php

<?php
setcookie('array_position', '0');
?>
<html>
<head>
    <style> 
        #lista{border: 1px solid red; height:300px; width: 300px; margin: 0 auto}
        #result{border: 1px solid blue; height:300px; width: 300px; margin: 10 auto}
    </style>
    <script>
        function add(e) {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
            xmlhttp.open("GET", "cali.php?q=" + e, true);
            xmlhttp.send();
        }
    </script>
</head>
<body>
    <div id="lista">
        <ul>
            <li id="test1" onclick="add('test1')">test1</li>
            <li id="test2" onclick="add('test2')">test2</li>
            <li id="test3" onclick="add('test3')">test3</li>
            <li id="test4" onclick="add('test4')">test4</li>
        </ul>
    </div>
    <div id="result">
        <ul>
            <li id="txtHint"></li>
        </ul>
    </div>
</body>
</html>

cali.php

<?php
// Get element ID.
$q = $_REQUEST["q"];
// Get the current array's position.
$position = $_COOKIE['array_position'];
setcookie('array['.$position.']', $q);
// Assign the Element ID on this Array. (1º Time must be array[0])
$num = $_COOKIE['array_position'];
// Loop for display all array values
for($i=0; $i<=$num; $i++){
    echo $_COOKIE['array'][$i]."</br>";
}
// the current array's position + 1 for next time.
$num2 = $_COOKIE['array_position']+1;
setcookie ('array_position', $num2) ;
?>

(请记住,每次重新加载页面时都要删除 cookie。) 有了这个,你第一次点击一个项目时会出现未定义的索引。如果继续单击项目,将出现上一个项目...

你必须改变这个:

echo $_COOKIE['array['.$possition.']'];

对此:

echo $_COOKIE['array'][$possition];

有关 setcookie() 的更多信息,请参阅手册:http://php.net/manual/en/function.setcookie.php

引自那里(例 3):

You may also set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name: