【发布时间】:2014-07-12 17:31:55
【问题描述】:
我正在开发一个 QA 应用程序,我需要根据要求动态地为一个问题添加多个答案。 为此,我发送了一个带有问题和答案的对象。
question={
'question_text':'what is your name',
'answers':[
{'answer_text':'some answer','isCorrect':'1'},
{'answer_text':'some answer','isCorrect':'1'},
{'answer_text':'some answer'} // answer may or may not have isCorrect key
]
}
在服务器端,我有两个表或迁移,1 个用于问题,1 个用于回答。答案表有三个字段question_id、answer_text' andisCorrect'。 question_id是答案表问题的外键。
存储对象我正在做的是
$question_text=Input::get('question_text');
$answers=Input::get('answers');
$question=new Question;
$question->question_text=$question_text;
$question->save();
foreach($answers as $ans){
$answer=new Answer;
$answer->question_id=$question->id;
$answer->answer_text=$ans->answer_text;
if($answer->isCorrect){
$answer->is_correct=$ans->isCorrect;
}
else{
$answer->is_correct=0;
}
$answer->save();
}
但是在迭代时出现错误
`production.ERROR: exception 'ErrorException' with message 'Trying to get property of non-object'`
我在这里做错了什么。我是第一次使用 PHP。我正在尝试像 Javascript 或 Python 那样迭代它。 告诉我如何获取答案数组对象的值并存储它们。
【问题讨论】:
-
$ans.answer_text;是什么意思? '。'是 PHP 中的文本连接运算符;这不是Java。你可能想要->。 -
另外,如果您不确定该属性是否存在,则不应使用
$answer->isCorrect。确定使用isset(),或者仅根据is_correct分配它:$answer->isCorrect = isset($ans->is_correct)? (int)$ans->is_correct : 0; -
那是-> PHP 的表示法。我已经纠正了。谢谢伊塞尔尼
-
你确定 Sajid 吗?检查您的数据库值。 Input::get('answers') 应该返回一个数组。所以 $ans 是一个数组,而不是一个对象。
-
答案是数组不是对象??我没有让你换班。
标签: php arrays laravel laravel-4 laravel-3