用逗号分隔的一个字符串中的POST数组,用逗号分隔

时间:2019-12-12 08:48:40

标签: php forms variables post

我从复选框中创建了一个表单,我希望所有选中的复选框都显示为一个变量(最终保存到MySQL)。

代码以表格形式显示复选框(工作正常):

...
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "<div class='form-check'>";
        echo "<label class='form-check-label'>";
        echo "<input class='form-check-input' name='prog[]' type='checkbox' value='".$row['name']."'>";
        echo "<span class='checkbox-icon'></span>";
        echo "<span class='form-check-description'>".$row['name']."</span>";
        echo "</label>";
        echo "</div>";
    }
}
...

在这里,我从输入中的复选框中显示数组:

...
$N = count($_POST['prog']);
for($i=0; $i < $N; $i++){
    echo "<div class='input-group input-group-sm mb-3'>
          <input name='programnames[]' value='".$_POST['prog'][$i]."' class='form-control' aria-label='Small' aria-describedby='inputGroup-sizing-sm' readonly>
          </div>";
}
...

问题是我在单独的输入框中看到了值。最终,我想实现一个字符串(变量)。要用逗号分隔的值,例如:(TextBox1.Val), (TextBox2.Val)

因此,如果我选择TomatoCucumber,我想包含在变量中:Tomato, Cucumber

1 个答案:

答案 0 :(得分:1)

prog应该是arraynull,因此您应该可以implode来使用它:

// Make sure we have an array, even if the data wasn't sent
$progChoices = $_POST['prog'] ?? [];
$joinedChoices = implode(',', $progChoices);

然后您就可以echo HTML了,

echo "<div class='input-group input-group-sm mb-3'>
      <input name='programnames' value='".$joinedChoices."' class='form-control' aria-label='Small' aria-describedby='inputGroup-sizing-sm' readonly>
      </div>";
相关问题