【问题标题】:PHP session records return only one recordPHP 会话记录只返回一条记录
【发布时间】:2023-03-27 04:00:02
【问题描述】:

我有多个会话记录 $_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';
}

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

【问题讨论】:

    标签: php session output record


    【解决方案1】:

    我的建议是这样的:-

    $_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】:

      改变

      echo '$to and $id';
      

      为:

      echo "$to and $id";
      

      因为 vars 不会在简单的带引号的字符串中进行解析。

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

      您可以array_push 将您的元素添加到您的购物车会话变量中以包含多个元素。并且仅当 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】:
        $_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>"; } }

        【讨论】:

        • 请对跨越多行的代码使用块格式 - 它是编辑器工具栏中的 {} 图标。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-21
        • 2016-05-22
        • 2018-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多