[英]Storing multiple values in $_SESSION array
我是 php 的新手,這個問題一直困擾着我。 我有三頁, 1. classpage.php ---- 其中包含,
<?php
session_start();
class addStock{
public function storeSessArray($stk_code){
array_push($_SESSION['recentlyView'],$stk_code);
}
}
?>
$_SESSION['recentlyView']=array();
$checkSession = new addStock;
$chkSession = $checkSession->storeSessArray($val);
echo '<pre>';
print_r($_SESSION);
echo '</pre>';
?>
和3. front.php持有
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title Page</title>
</head>
<body>
<?php
$val='5';
?>
<?php
include 'logic.php';
?>
</body>
</html>
當有人加載front.php時,我想保留存儲在$_SESSION['recentlyView']
數組中的值數組。 但是每次我為 $val 分配不同的值時,只有存儲在 $val 中的最后一個值出現在$_SESSION['recentlyView']
數組中。 我希望$val
中使用的每個值都存儲在$_SESSION['recentlyView']
試試這個,它應該可以解決你的問題。
class addStock{
public function storeSessArray($stk_code){
$_SESSION['recentlyView'][] =$stk_code;
}
}
在有任何 output 之前,您必須調用session_start()
。 文檔說明
要使用基於 cookie 的會話,必須在向瀏覽器輸出任何內容之前調用 session_start()。
As you've presented your code, the very first thing that is loaded is front.php
which includes logic.php
which calls the class in classpage.php
. (我看不到該頁面是如何被引用的——無論是通過 include 還是 spl。
您將演示文稿與邏輯分開的想法是正確的,但是您的順序倒退了。 需要發生的第一件事是執行和加載相關的 php 代碼,演示是最后發生的事情。 不幸的是,在您的腳本中發生的第一件事就是它立即啟動 output。
解決方案是通過 index.php 匯集所有請求(查找如何進行 seo 友好的 url),然后使用“前端控制器”或“路由器”。
Short of that, you need to include a brief php section on top of front.php, so that session start is called before output.
<?php
session_start();
include 'logic.php'; // don't print anything from your logic; pass back a variable to print below.
?>
<!DOCTYPE html>
<html lang="">
....
您可能會繼續覆蓋 session 數組。 嘗試檢查它是否已經設置:
if(!isset($_SESSION['recentlyView']))
$_SESSION['recentlyView'] = array();
這只會設置一次數組,然后您的方法將添加到其中。
另外,如另一個答案中所述,請確保將session_start();
在最開始的最頂層頁面中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.