Laravel,检查会话数组是否有值

时间:2014-12-09 17:19:48

标签: php arrays session laravel

如果会话数组中已存在某个值,我该如何检查?我正在尝试在Session数组中存储活动树对象来打开和关闭它们:

public function postSelected()
{
    $id = Input::get('id');
    if (Session::has('user.selection', $id)) { // check?
        Session::pull('user.selection', $id);
    } else {
        Session::push('user.selection', $id);
    }

    return Response::json(Session::get('user.selection'), 200);
}

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

假设您尝试做的事情类似于切换(如果存在则删除,如果丢失则添加):

$index = array_search($id, $selection = Session::get('user.selection', []));

if ($index !== false)
{
    array_splice($selection, $index, 1);
}
else
{
    $selection[] = $id;
}

Session::set('user.selection', $id);