首页 > 解决方案 > 如何在 value 属性中传递多个参数并将它们放在 name 属性中的关联数组中?

问题描述

是否可以将多个参数放在 value 属性中并将它们放在 name 属性中的关联数组中?

我应该这样做吗?

我正在尝试使用引导程序自定义选择https://getbootstrap.com/docs/4.0/components/input-group/来实现这一点

自定义选择

我需要传递collaborator_id和card_id(card_id在上面的代码中分配)见下面的代码

<form action="card/add_participant" method="POST">
    <label for="add_participant">Add participant</label>
    <div class="input-group">
        <select name="participantAndCard[]" class="custom-select" id="add_participant">
            <option selected>Choose participant</option>
            <?php foreach ($collab as $c) : ?>
                <option value="collaborator_id => <?=$c->id?>, card_id => <?=$card->id ?> "><?= $c->full_name ?></option>
            <?php endforeach; ?>
        </select>
        <div class="input-group-append">
            <button class="btn btn-primary" type="submit">Button</button>
        </div>
     </div>
</form>

在服务器端

public function add_participant(){
   $participantAndCard = $_POST['participantAndCard'];
   var_dump($participantAndCard);
  }

我得到一个里面有一个字符串的数组。

array(1) { [0]=> string(37) "collaborator_id => 33, card_id => 73 " }

我究竟做错了什么?如何解决这个问题?

标签: phpformstwitter-bootstrap

解决方案


首先,您不想participantAndCard[]只使用 use将选择输入作为数组传递participantAndCard

<select name="participantAndCard" class="custom-select" id="add_participant">

然后创建一个数组并将其编码为 JSON:

<option value='<?= json_encode(['collaborator_id'=>$c->id, 'card_id'=>$card->id]); ?>'><?= $c->full_name ?></option>

然后在 PHP 中解码:

$participantAndCard = json_decode($_POST['participantAndCard'], true);

如果出于某种原因您需要participantAndCard成为一个数组,则participantAndCard[]在选择中使用名称,然后在 PHP 中循环:

foreach($_POST['participantAndCard'] as $value) {
    $participantAndCard[] = json_decode($value, true);
}

推荐阅读