echo会话数组值-warning非法字符串偏移量


echo Session array value- warning Illegal string offset

我正试图使用SESSION将cart函数添加到网站中,项目已存储到SESSION中,但我有以下警告:当我尝试回显数组值时,字符串偏移量"pcode"非法

$itemArray = array('pcode'=>$_GET['code']);
$_SESSION['cart_item'] = $itemArray;

这就是我将数组存储到会话中的方式

foreach ($_SESSION['cart_item'] as $item){
                echo $item['pcode'];
                }

这就是我回显存储阵列的方式。我是PHP的新手,一直在尝试从头开始构建网站。我想知道为什么警告一直显示在我的页面上。感谢

只有$item会给你价值:

$itemArray = array('pcode'=>'aaa');
$_SESSION['cart_item'] = $itemArray;
foreach ($_SESSION['cart_item'] as $key=>$item){
    echo $key; // this will print "pcode"
    echo $item; // this will print "aaa"
}

将数据附加到会话:

$data = $_SESSION['cart_item']; // first get session data into any array
$data['newdata'] = 'newvalue'; // now add data 
$_SESSION['cart_item'] = $data; // again write session with newly added array

echo $item当您使用foreach时,您将获得$item['code']值,foreach为您提供key=>值对,因此'pcode'是键,$_get['code']是foreach中的值,由于您仅使用$item,它将指向$_get['code'']值。

$_GET['code']='www';
$itemArray = array('pcode'=>$_GET['code']);
$_SESSION['cart_item'] = $itemArray;
foreach ($_SESSION['cart_item'] as $item){
                echo $item;
                }

数组项中没有pcode键。

有一种方法可以检查是否有密钥array_key_exists

bool array_key_exists ( mixed $key , array $array )

找到内容的任何更简单的方法都是打印数组并死亡,看看数组的内容是否正确,修复并重试。