【发布时间】:2014-10-15 06:32:30
【问题描述】:
我正在构建一个系统,它从 POST 方法捕获信息并将它们添加到 PHP $_SESSION。我要遵循的基本逻辑是:
- 检查方法并调用相关函数
- 通过函数检查
$_SESSION数据是否已经存在 - 通过函数检查
$post_id变量是否已经在$_SESSION的数组中 - 根据这些函数的结果,添加到数组、创建新数组或什么都不做
到目前为止,这是我为处理此逻辑而编写的代码。我希望首先让 add_to_lightbox() 函数工作,然后再转到其他两个函数。
session_start();
// set variables for the two things collected from the form
$post_id = $_POST['id'];
$method = $_POST['method'];
// set variable for our session data array: 'ids'
$session = $_SESSION['ids'];
if ($method == 'add') {
// add method
add_to_lightbox($post_id, $session);
} elseif ($method == 'remove') {
// remove method
remove_from_lightbox($post_id);
} else ($method == 'clear') {
// clear method
clear_lightbox();
}
function session_exists($session) {
if (array_key_exists('ids',$_SESSION) && !empty($session)) {
return true;
// the session exists
} else {
return false;
// the session does not exist
}
}
function variable_exists($post_id, $session) {
if (in_array($post_id, $session)) {
// we have the id in the array
return true;
} else {
// we don't have the id in the arary
return false;
}
}
function add_to_lightbox($post_id, $session) {
if (!session_exists($session) == true && variable_exists($post_id, $session) == false) {
// add the id to the array
array_push($session, $post_id);
var_dump($session);
} else {
// create a new array with our id in it
$session = [$post_id];
var_dump($session);
}
}
它一直处于一种状态,它总是到达add_to_lightbox() 并且每次都跟随array_push($session, $post_id);。由于嵌套函数,我不确定我编写的这段代码是否可行,以及如何重构它以使功能正常工作。
【问题讨论】:
-
array_key_exists('ids',$_SESSION)你可以只做isset($_SESSION['ids']),!session_exists($session) == true,只是!session_exists($session)和variable_exists($post_id, $session) == false只是!variable_exists($post_id, $session)。同样array_push($session, $post_id);不修改原始数组,只修改其本地副本。使用function add_to_lightbox($post_id, &$session)和$session = [$post_id];不会更新$_SESSION数组。 -
效果很好,谢谢。
标签: php arrays function session session-variables