代码之家  ›  专栏  ›  技术社区  ›  user9107323

PHP会话记录只返回一条记录

  •  1
  • user9107323  · 技术社区  · 7 年前

    我有多个会话记录 $_SESSION["cart_array"] 喜欢

    $_SESSION["cart_array"] = array(0 => array("item_id" => sms, "quantity" => $pe, "to" =>$to, "msg" => $message));
    

    请看这里 https://ideone.com/NZysQc

    在我的成就中,我试图在不同的页面中输出此记录,但它只输出一条记录。我做错了什么?这是我的试用代码:

    foreach ($_SESSION["cart_array"] as $each_item) {
        $id = $each_item['item_id'];
        $to = $each_item['to'];
        echo '$to and $id';
    }
    

    但它在会话中只返回一条记录。

    3 回复  |  直到 7 年前
        1
  •  1
  •   Death-is-the-real-truth    7 年前

    我的建议如下:-

    $_SESSION["cart_array"][] = array("item_id" => $sms, "quantity" => $pe, "to" => $to, "msg" => $message);
    

    要形成阵列

    foreach ($_SESSION["cart_array"] as $each_item) {
        $id = $each_item['item_id'];
        $to = $each_item['to'];
        echo "$to and $id";
    }
    

    对于循环,请注意 echo .

        2
  •  0
  •   jeprubio    7 年前

    改变

    echo '$to and $id';
    

    适用于:

    echo "$to and $id";
    

    因为变量不会在简单带引号的字符串中解析。

    您的示例只有元素0,因此只显示一个元素。

    你可以 array_push 您的元素将会话var包含多个元素。并且仅当var仍然未设置时,才将其设置为新数组。

    $newItem = array("item_id" => sms, "quantity" => $pe, "to" =>$to, "msg" => $message);
    if (empty($_SESSION["cart_array"]))
        $_SESSION["cart_array"] = array(0 => $newItem);
    else
        array_push($_SESSION["cart_array"], $newItem);
    
        3
  •  -1
  •   Shailesh Dwivedi    7 年前
    $_SESSION["cart_array"] = array(0 => array("item_id" => sms, "quantity" => $pe, "to" =>$to, "msg" => $message),1 => array("item_id" => sms, "quantity" => $pe, "to" =>$to, "msg" => $message));
    

    foreach($_SESSION["cart_array"] as $each_item_array) { foreach ($each_item_array as $each_item) { $id = $each_item['item_id']; $to = $each_item['to']; echo "$to and $id </br>"; } }