【发布时间】:2018-03-02 07:28:23
【问题描述】:
我有一个包含一些数组输入字段的表单,例如name[],age[],gender[] 等。
我正在尝试使用
$name = $request->getParam('name');
但我没有得到任何数据。任何形式的帮助将不胜感激。提前致谢。
【问题讨论】:
-
您可以将数据作为 JSON 对象传递。有关更多信息,请查看下面的答案。
我有一个包含一些数组输入字段的表单,例如name[],age[],gender[] 等。
我正在尝试使用
$name = $request->getParam('name');
但我没有得到任何数据。任何形式的帮助将不胜感激。提前致谢。
【问题讨论】:
如果你想传递一个对象数组,你可以通过传递 JSON 格式的值来实现。
例如:
我的示例JSON 格式如下。
{
"news_title": "Title",
"news_description": "news_description",
"news_date": "03-12-2017",
"image_list": [
{
"imagedata": "data",
"fileName": "Imags12.png"
},
{
"imagedata": "data",
"fileName": "Imags11.png"
}
]
}
您可以在slim 中读取此JSON 数据,如下所述。
$app->post('/create_news_json', function () use ($app) {
$json = $app->request->getBody();
$data = json_decode($json, true); // parse the JSON into an assoc. array
$news_title=$data['news_title']; // to retrieve value from news_title
$news_description=$data['news_description']; // to retrieve value from news_description
$news_date = date_format(date_create($data['news_date']),"Y-m-d"); // to
retrieve value from news_date and convert the date into Y-m-d format
$news_ImageList=$data['image_list']; //read image_list array
$arr_length=count($data['image_list']);//calculate the length of the array.
// trace each elements in image_list array as follows.
for($i=0;$i<count($news_ImageList);$i++)
{
$imagedata = $news_ImageList[$i]['imagedata']; //read image_list[].imagedata element
$filename = $news_ImageList[$i]['fileName']; //read image_list[].fileName element
}
});
在 postman 中,您可以在正文部分以 application/json 格式将 JSON 对象作为行数据传递。
通过使用这个概念,任何类型的复杂数据结构都可以作为 JSON 对象传递到 slim 中。它可以完成大多数数据传递的目标。
【讨论】:
echo $json 显示变量,只需在$json 变量中显示您的值
看起来你有一个大致的想法,但是在查看文档之后。看来您需要为发布数据使用 slim 的助手。这是文档显示的示例,用于检索 title 和 description 的值。如下所述,filter_var() 不是必需的,但强烈推荐和良好的做法,以便通过删除任何可能造成伤害的特殊字符来增加额外的保护级别。
$app->post('/ticket/new', function (Request $request, Response $response) {
$data = $request->getParsedBody();
$ticket_data = [];
$ticket_data['title'] = filter_var($data['title'], FILTER_SANITIZE_STRING);
$ticket_data['description'] = filter_var($data['description'], FILTER_SANITIZE_STRING);
// ...
https://www.slimframework.com/docs/tutorial/first-app.html,如果您想了解更多相关信息,请点击此链接。
【讨论】:
$names = $request->getParam('name');
$genders = $request->getParam('gender');
$ages = $request->getParam('age');
$persons = array();
for($i=0;$i<count($names);$i++){
$arr['name'] = $names[$i];
$arr['gender'] = $genders[$i];
$arr['age'] = $ages[$i];
array_push($persons,$arr);
}
【讨论】:
您可以使用
访问 html 表单发送的表单数据$name=$req->getParsedBodyParam("name");
【讨论】: