【问题标题】:How do I echo a specific part of this session array?如何回显此会话数组的特定部分?
【发布时间】:2019-01-25 12:55:10
【问题描述】:

当尝试打印/回显会话数组的特定部分时,它不会返回除“1”之外的任何内容

它还给出了一个错误,告诉我 user_name 是一个未定义的索引,但是当我 var_dump 我的会话时它显示它存在。

在屏幕上仅显示我的会话的user_name 部分的正确方法是什么?

我试过print_rechoprint,但这些似乎都不起作用

session_start();

include '../php/database.php';
var_dump($_SESSION['userdata']);
echo "Welcome back " . print_r($_SESSION['userdata']['user_name'][0]) . "!";

我希望输出是“Welcome back user_name”,在这种情况下应该是文本字符串“empty”

var_dump:

array(1) { [0]=> array(1) { [0]=> array(8) { ["user_id"]=> string(1) "1" [0]=> string(1) "1" ["user_name"]=> string(5) "empty" [1]=> string(5) "empty" ["user_pass"]=> string(5) "empty" [2]=> string(5) "empty" ["user_email"]=> string(17) "empty@hotmail.com" [3]=> string(17) "empty@hotmail.com" } } }

输出

注意:未定义索引:user_name in C:\xampp\htdocs\Projecten\loginSystem\pages\dashboard.php 在第 7 行 欢迎回来 1!

【问题讨论】:

标签: php arrays session echo


【解决方案1】:

您的会话中有 2 个数组 这样做:

echo "Welcome back " . print_r($_SESSION['userdata'][0][0]['user_name']) . "!";

【讨论】:

    【解决方案2】:

    正如你提到的,你的会话数据是这样的:

    array(1) {
        [0]=> array(1) { 
            [0]=> array(8) { 
                ["user_id"]=> string(1) "1" [0]=> string(1) "1" 
                ["user_name"]=> string(5) "empty" [1]=> string(5) "empty" 
                ["user_pass"]=> string(5) "empty" [2]=> string(5) "empty" 
                ["user_email"]=> string(17) "empty@hotmail.com" [3]=> string(17) "empty@hotmail.com" 
            } 
        } 
    }
    

    要获得 user_name,您必须通过以下方式遍历您的数组:

    echo $_SESSION['userdata'][0][0]['user_name'];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 2021-12-26
      • 2020-01-01
      • 2015-09-14
      • 2014-06-04
      • 1970-01-01
      相关资源
      最近更新 更多