php - 如何在 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 " }
我究竟做错了什么?如何解决这个问题?
解决方案
首先,您不想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);
}
推荐阅读
- tfs - 用于 ID/KEY 的 Azure DevOps Extension 自定义服务端点
- fullcalendar - 列表视图 - 选择特定日期
- sql - UPDATE SET field=CONCAT("string", field) 上的重复条目
- c# - How to select last hour and groupby minute?
- android - 未显示 RecyclerView 的文档
- python-3.x - 使用循环和列表
- swift - CAShapeLayer 填充颜色将保持白色
- java - 为什么选择ConcurrentModificationException的设计标准只是结构修改
- android - 使用 Tasker 和 Spotify 像 Android 一样睡觉
- c++ - 如何在 Qt 中取消转义字符串?