当按下按钮时,如何使用自定义键将文本框中的值添加到 PHP,而不覆盖现有数组

发布于 2025-01-16 03:09:42 字数 1152 浏览 4 评论 0原文

我在 HTML 表单中有一个文本框。我试图让 PHP 将该文本框的值作为具有其他值(例如单词“bob”)的键添加到 PHP 数组中。该数组应该是持久的,不应该每次都用新值覆盖,而是在单击按钮时应将更多值添加到数组中。

我的 HTML 表单如下所示:

<form action="" method="post">
<textarea id="dl-textarea" name="dl-textarea" rows="4" cols="50"></textarea>
<input type="submit" value="Add to array" name="submitText"/>
</form>

我当前拥有的 PHP 是:

<?php
session_start();
if (isset($_POST["dl-textarea"])) {
    if ($_SESSION["array"] != ""){
        $_SESSION["array"] .= ",";
    }
    $_SESSION["array"] .= $_POST["dl-textarea"];
} else {
    $_SESSION["array"] = "";
}

$demo = $_SESSION["array"] == "" ? "gg" : $_SESSION["array"];
print_r($demo);

我从以下 StackOverflow 答案中获取的。 每次单击提交按钮时如何为数组创建添加值?在 php 中(带有会话) 这会将新值插入到具有常规键(0、1、2 等)的数组中。但是,我希望对键进行一些控制,以便将文本区域的内容作为我的键,将另一个值作为我的数据(例如,如果文本区域包含单词“text1”,那么当我单击我的按钮会将其插入到数组中,其中“text1”作为键,其他内容作为数据,然后,如果文本区域包含单词“text2”,则单击该按钮会将其添加到数组中。最终数组可能如下所示: ['text1':'鲍勃','text2':'鲍勃','text3':鲍勃'])

I have a textbox within a HTML form. I'm trying to get PHP to add the value of that textbox to a PHP array as a key with a value of something else (for example, the word "bob"). The array should be persistent, it shouldnt be overwritten with new values each time, rather as the button is clicked further values should be added to the array.

My HTML form looks like this:

<form action="" method="post">
<textarea id="dl-textarea" name="dl-textarea" rows="4" cols="50"></textarea>
<input type="submit" value="Add to array" name="submitText"/>
</form>

And the PHP I currently have is:

<?php
session_start();
if (isset($_POST["dl-textarea"])) {
    if ($_SESSION["array"] != ""){
        $_SESSION["array"] .= ",";
    }
    $_SESSION["array"] .= $_POST["dl-textarea"];
} else {
    $_SESSION["array"] = "";
}

$demo = $_SESSION["array"] == "" ? "gg" : $_SESSION["array"];
print_r($demo);

Which I picked up from the following StackOverflow answer.
How to create add value to array everytime i click submit button? in php (with session)
This inserts new values into the array with conventional keys (0, 1, 2, and so on). However, I would like to have some control over the keys so as to have the contents of the textarea as my key, and another value as my data (for example, if the textarea contained the word "text1", then when I click my button it would insert this into the array with "text1" being the key and something else as the data. And then afterwards, if the text area contained the word "text2", then clicking the button would add that to the array. So a final array might look like: ['text1':'bob','text2':'bob','text3':bob'])

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文