猿问

从输入创建数组?

我希望在单个字段 (json) 中的表单上存储任意数量的问题答案。

所以输入可能是这样的:

你的工作:

  • 职称

  • 开始日期

  • 结束日期

我知道我可以调用输入<input name="job_title[]">,这些都将在job_title. 但是无论如何,只要以特定方式命名输入,就可以将所有三个输入都列在一个键控数组下,例如:

[jobs => [['job_title' => 'xyz', 'start_date` => 'xyz', 'send_date` => 'xyz'], ....]

或者我需要用循环在 php 中手动构建它吗?


慕工程0101907
浏览 184回答 2
2回答

跃然一笑

您想根据 Posted 输入值创建一个数组吗?只需将 foreach 循环与$_POST变量一起使用<?php&nbsp;if (isset($_POST)) {&nbsp; &nbsp; foreach ($_POST as $key => $value) { // for every post value&nbsp; &nbsp; &nbsp; &nbsp; $array[] = array( // we create a array based on the name and the value&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $key => $value&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }&nbsp; &nbsp; var_dump($array); // dump the array}?><form method="POST">&nbsp; &nbsp; <input type="text" name="job title" value="xyz">&nbsp; &nbsp; <input type="text" name="start date" value="xyz">&nbsp; &nbsp; <input type="text" name="send date" value="xyz">&nbsp; &nbsp; <!-- any other input -->&nbsp; &nbsp; <button type="submit">sd</button></form>该var_dump($array)会给你array(2) { ["job_title"]=> string(3) "xyz" ["start_date"]=> string(3) "xyz" } array(1) { ["send_date"]=> string(3) "xyz" }要从数组创建 JSON,只需执行echo json_encode($array)
随时随地看视频慕课网APP
我要回答