首页 > 解决方案 > 如何从提取函数()将数组插入 $_SESSION()?

问题描述

我的 home.php 文件中有一个函数get_teacher_info()。它从 mysql 查询返回一个数组。我将它存储在$data变量中。

现在我想将'key'=>'value'数组中的每一对设置为单独的变量。所以我正在使用extract()

如何设置我从中接收的会话变量extract()

我的代码如下。

$data = $teacher->get_teacher_info();
$_SESSION[]= extract($data);

标签: phparraysphp-7

解决方案


你可以像这样使用它

$data = $teacher->get_teacher_info();

// if there is addtional data in the `$_SESSION` before assigning data extracted from DB you can use the `array_merge`, this will keep previous data from `$_SESSION`
$_SESSION = array_merge($_SESSION, $data);

// If there is no additional data then directly assign the data from DB to `$_SESSION` only if the `$data` is already an associative array
$_SESSION = $data;

推荐阅读