在关联数组中设置输入,然后循环遍历条目


setting input in an associate array then loop through the entries

我有一个由用户输入填充的关联数组。然后,我将该数组设置为会话变量,以便每次输入新的内容时,我都可以在数组的顶部添加内容。

警告:为foreach()提供了无效参数

<?php session_start(); ?>
<h1>
    <?php 
        foreach ($_SESSION['formOneArrayGlobal'] as $x => $xValue) {
            echo $x . $xValue;
        }
    ?>
</h1>
<form action="send.php" method="post" name="form-one">
    <input type="text" name="name">
    <input type="text" name="number">
    <button type="submit">Submit</button>
</form>
<?php
    session_start();
    try {
        if (!empty($_POST['form-one'])) {
            $variableOne = $_POST['name'];
            $variableTwo = $_POST['number'];
            $formOneArray[$variableOne] = $variableTwo;
            $_SESSION['formOneArrayGlobal'] = $formOneArray;
    } catch(Exception $e) {
        echo $e;
    }
?>

如果$_SESSION['formOneArrayGlobal']中没有数据,您必须在第一次检查

 if(isset($_SESSION['formOneArrayGlobal']) && !empty($_SESSION['formOneArrayGlobal'])){ 
             foreach ($_SESSION['formOneArrayGlobal'] as $x => $xValue) {
                echo $x . $xValue;
            }
    }

我宁愿直接检查您存储的变量的值是否真的是一个数组。只是检查它是否为空并不能真正帮助你,如果它是一个字符串,你仍然会得到警告。

if (is_array($_SESSION['formOneArrayGlobal'])) {
    foreach ($_SESSION['formOneArrayGlobal'] as $x => $xValue) {
        echo $x . $xValue;
    }
}