简体   繁体   English

将数组设置为PHP中的会话变量,然后访问它

[英]Setting an array as a session variable in PHP and then accessing it

If I have an array: 如果我有一个数组:

$resultArr = pg_fetch_array($result,NULL ); $resultArr = pg_fetch_array($result,NULL );

and at the top of my php code I declare: 在我的php代码顶部,我声明:

$_SESSION['resultArr'] = $resultArr;

Why can't I access the array elements like so: 为什么我不能像这样访问数组元素:

for($i = 0; $i < $NUM_COLUMNS; $i++){
    // creation of the table and row are handled elsewhere.
    // The table is also within a <form> if that matters
    echo "<td>" .$_SESSION['resultArr'][$i]."</td>";
}

My table ends up having empty columns and I can't figure out why... 我的桌子最后有空的列,我不知道为什么...

EDIT: I figured it out. 编辑:我想通了。 I was declaring $_SESSION['resultArr'] = $resultArr; 我在声明$_SESSION['resultArr'] = $resultArr; at the top of my code (right after session_start()) and it wasn't getting set. 在我的代码顶部(session_start()之后),并且没有设置。 I moved it down to the point right after $resultArr = pg_fetch_array($result,NULL); 我将其移至$resultArr = pg_fetch_array($result,NULL);

Is this how it's supposed to work or should it have worked fine at the top of the code? 这是应该工作的方式还是应该在代码顶部正常工作?

也许您提到了,但没有提及,但是您必须在$_SESSION上的任何操作之前调用session_start()

after your edit, yes this is how it is supposed to work, you first need to declare $resultArr , then put it's value in the session array 编辑之后,是的,这就是应该的工作方式,您首先需要声明$resultArr ,然后将其值放入会话数组中

beacause in php you are no longer working with pointers, $_SESSION['resultArr'] = $resultArr; 因为在php中您不再使用指针,所以$_SESSION['resultArr'] = $resultArr; mean "$_SESSION['resultArr'] takes all the values of $resultArr at that precise moment", but it does not mean "they are thesame, if one changes, then the other changes too" . 意思是“ $ _SESSION ['resultArr']在该精确时刻获取$ resultArr的所有值”,但这并不意味着“它们相同,如果一个改变,那么另一个也会改变”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM