循环对象数组并在 Laravel PHP 中获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23827825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop over an array of objects and get values in laravel PHP
提问by Sajid Ahmad
I am working on a QA app where i need to add multiple answers to a question as per requirement dynamically. for this i am sending an object which carry question and the answers like.
我正在开发一个 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
]
}
On server side I have two tables or migrations 1 for Question and 1 for answer. The answer table have three fields question_id
, answer_text' and
isCorrect'. question_id
is the foreign key of question in answer table.
在服务器端,我有两个表或迁移 1 用于问题,1 用于回答。答案表有三个字段 question_id
,answer_text' and
isCorrect'。question_id
是答案表中问题的外键。
to store the objects what i am doing is
存储对象我正在做的是
$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();
}
But while iterating there is an error
但是在迭代时出现错误
`production.ERROR: exception 'ErrorException' with message 'Trying to get property of non-object'`
what wrong I am doing here. I am first time working on PHP. I am trying to iterate it like Javascript or Python way. Tell me how can i get the values of answers array object and store them.
我在这里做错了什么。我是第一次使用 PHP。我正在尝试像 Javascript 或 Python 那样迭代它。告诉我如何获取答案数组对象的值并存储它们。
回答by Laurence
You dont seem to be referencing the array variables correctly. This should work:
您似乎没有正确引用数组变量。这应该有效:
foreach($answers as $ans){
$answer=new Answer;
$answer->question_id=$question->id;
$answer->answer_text=$ans['answer_text'];
$answer->is_correct = isset($ans['isCorrect']);
$answer->save();
}
p.s. Im not sure about forEach
- I'm suprised it works - but you should probably rename it to foreach
to confirm to the normal standards
ps我不确定forEach
- 我很惊讶它的工作原理 - 但你可能应该将它重命名为foreach
以确认正常标准