我想知道是否可以编辑在 foreach
循环中处理的当前对象
我正在处理一组对象 $questions
,我想在我的数据库中查找与该问题对象相关的答案。因此,对于每个问题,请获取答案对象并更新当前 $question
inside 我的 foreach
循环,以便我可以在其他地方输出/处理。
foreach($questions as $question){
$question['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
最佳答案
有两种方法可以做到这一点
foreach($questions as $key => $question){
$questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
这样可以保存 key ,以便在主 $questions
变量中再次更新它
或
foreach($questions as &$question){
添加 &
将使 $questions
保持更新。但我会说第一个是推荐的,即使它更短(见 Paystey 的评论)
根据 the PHP foreach
documentation :
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
关于php - 在 foreach 循环中修改数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10121483/