我正在寻找这是否可能。
我希望使用 PHP 作为中间件将一组多个值发布到服务器。我有一个移动应用程序,用户将在其中完成问卷调查。我想在一个 api 调用中发布每个问题的问题、答案和日期。
是否可以发布和处理一组值。类似答案 = [[问题,答案,日期],[问题,答案,日期],[问题,答案,日期],[问题,答案,日期]]
任何想法或最佳实践请在下面发布。
更新:如果可能的话,您可以提供一个示例或链接吗?
你可以通过几种不同的方式来做到这一点。第一种方法是发布一个数组并像这样访问它:
foreach($_POST['answers'] as $answer){
$thisQuestion = $answer['question'];
$thisAnswer = $answer['answer'];
$thisDate = $answer['date'];
// Do something with this current Question/Answer/Date combo
}
第二种方法是发送一个json
字符串并在 PHP 中对其进行解码:
$answers = json_decode($_POST['answer']);
您选择的方法实际上归结为最容易发送数据的方式。
检查这个 O'Really Array 的 PHP 手册。它真的对我使用数组进行编程有很大帮助。
最快/最黑客的方法是在每组上放一个数字并以这种方式解析出来。换句话说,实际上不要传递数组,而是传递值:[question0,answer0,date0],[question1,answer1,date1] 等。其他选项包括为每个选项传递数组(我相信你可以这样做),传递 JSON (www.json.org) 或数组的序列化,这有点复杂。希望这三个中的一个会有所帮助。:)
是的,你绝对可以做到这一点。试试下面的代码片段:
<?php
if($_POST) {
echo $_POST ['questions'][1];
echo $_POST ['questions'][2];
var_dump($_POST);
}
else {
?>
<form method="post">
<input type = "text" name = "questions[2]">
<input type = "text" name= "questions[1]">
<input type="submit" name = "submit" value "Submit">
</form>
<?php
}
?>
现在,如果您world
在第一个文本输入和hello
第二个输入中提交,您将看到helloworld
我回应它的方式。
甚至你可以自己设置这个数组的索引,你可以看到我已经设置了它。这是 $_POST 数组的 var_dump,让您更清楚:
array(2) {
["questions"]=>
array(2) {
[2]=>
string(5) "world"
[1]=>
string(5) "hello"
}
["submit"]=>
string(0) ""
}
希望能消除您的困惑。根据您的需要修改它。快乐的编码伙伴:)
当然在 PHP 和 HTML 中你会做这样的事情:
<?
for($i=0;$i<10;$i++) {
echo "<input type=text name='qa[$i][question]'>";
echo "<input type=text name='qa[$i][answer]'>";
echo "<input type=text name='qa[$i][date]'>";
}
?>
但听起来您希望在没有浏览器的情况下发布值,您可以简单地手动构建您的发布字符串并使用 PHP 的 curl 支持。
通常,您将通过循环遍历可用值并调用urlencode
以正确编码 POST 字符串来构造 POST 字符串。
<?
$poststr = "qa[0][question]=some+question&qa[0][answer]=some+anser&qa[0][date]=2012-10-02&qa[1][question]=another+question&qa[1][answer]=another+answer&qa[1][date]=2012-09-27";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $poststr);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec ($ch);
curl_close ($ch);
?>
然后获取值(对于上述任一方法)
<?
$answer_array = $_POST['qa'];
?>
$answer_array
将基本上格式化如下:
$answer_array = array(
0 => array(
"question"=>"some question",
"answer"=>"some answer",
"date"=>"2012-10-02"),
1 => array(
"question"=>"another question",
"answer"=>"another answer",
"date"=>"2012-09-27")
);
我会让每个表单元素名称都像这样的数组
<input type='text' name='question[]' />
<input type='text' name='answer[]' />
<input type='text name='date[]'/>
现在,您可以根据需要多次重复这些表单元素,并且每个值都将存储为数组中的一个位置。例如,如果您有 5 个问题,您可以访问第五个问题的值,例如:
<?php
$questions = $_POST['question];
$fifth_question = $questions[4] //arrays start at position 0 so 4 would be the 5th position
您还可以遍历每个表单元素数组并创建一个像上面请求的多维数组。那看起来像:
<?php
$questions = $_POST[question'];
$answers = $_POST['answer'];
$date = $_POST['date'];
$combined = array();
for($i = 0; $i < count($questions); $i++_
{
$combined[] = array('question'=> $questions[$i],
'answer'=>$answers[$i], 'date'=>$dates[$i]);
}
希望这有帮助。