简体   繁体   English

获取$ _SESSION数组值并使用echo显示

[英]Obtaining $_SESSION array values and displaying using echo

I have the ff code which stores values inputted in form's textfield to a session array which I named "numbers". 我有ff代码,它将在表单的文本字段中输入的值存储到我称为“数字”的会话数组中。 I need to display the value of the array but everytime I try echo $value; 我需要显示数组的值,但是每次我尝试echo $value; I get an error Array to string conversion in 我收到一个错误Array to string conversion in

I used echo var_dump($value); 我用echo var_dump($value); and verified that all the inputted values are stored to the session array. 并验证所有输入的值都已存储到会话数组中。

My goal is to store the user input to an array everytime the user hits the submit button. 我的目标是每次用户单击“提交”按钮时将用户输入存储到数组中。

How do I correct this? 我该如何纠正?

<?php 
    session_start();
?>

<html>
<head>
    <title></title>
</head>
<body>
    <form method="POST" action="index.php"> 
        <label>Enter a number</label>&nbsp;
        <input type="text" name="num" required />
         <button type="submit">Submit</button> 
    </form>
</body>
</html>

    <?php
    if (isset($_POST["num"]) && !empty($_POST["num"])){
        $_SESSION['numbers'][] = $_POST["num"];

        foreach($_SESSION as $key => $value){
            echo ($value);
        }
    }
    ?>

Thank you. 谢谢。

When doing $_SESSION['numbers'][] = $_POST["num"]; 当做$_SESSION['numbers'][] = $_POST["num"]; , you are making $_SESSION['numbers'] an array: so you'll either need to do that differently, or check whether $value within your foreach loop is an array or not. ,您正在将$_SESSION['numbers']制成数组:因此,您需要以不同的方式进行操作,或者检查您的foreach循环中的$value是否$value数组。

if (isset($_POST["num"]) && !empty($_POST["num"])){
    $_SESSION['numbers'][] = $_POST["num"];

    foreach($_SESSION as $key => $value){
        if (is_array($value)) {
            foreach ($value as $valueNested) {
                echo ($valueNested);
            }
        } else {
            echo ($value);
        }
    }
}

OR 要么

if (isset($_POST["num"]) && !empty($_POST["num"])){
    $_SESSION['numbers'] = $_POST["num"];

    foreach($_SESSION as $key => $value){
        echo ($value);
    }
}

The latter is probably what you are actually trying to accomplish. 后者可能是您实际上要实现的目标。

The error is because SESSION[“numbers”] is an array and you can just echo an array. 该错误是因为SESSION [“ numbers”]是一个数组,您可以仅回显一个数组。 It will throw an error “Array to string converstion”. 它将引发错误“数组到字符串对话”。

Iterate through the array and print it instead. 遍历数组并打印。

If you want to echo all entered numbers, your for each cycle should be: 如果要回显所有输入的数字,则每个周期的数字应为:

foreach($_SESSION[‘numbers’] as $key => $value) {
    echo $value;
}

This is because the $_SESSION['numbers'] itself is the array that contains the numbers. 这是因为$ _SESSION ['numbers']本身就是包含数字的数组。

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

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