在foreach循环中修改数组值

问题描述:

我想知道是否有可能编辑在 foreach 循环中处理的当前对象

I was wondering if it is possible to edit the current object that's being handled within a foreach loop

我正在处理对象数组 $ questions ,我想遍历数据库中查找与该问题对象相关的答案.因此,对于每个问题,请获取答案对象并更新我的 foreach 循环中的当前 $ question 内部,以便我可以在其他地方输出/处理.>

I'm working with an array of objects $questions and I want to go through and look for the answers associated with that question object in my db. So for each question go fetch the answer objects and update the current $question inside my foreach loop so I can output/process elsewhere.

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']);
}

通过这种方式保存密钥,因此您可以在主 $ questions 变量中再次对其进行更新

This way you save the key, so you can update it again in the main $questions variable

foreach($questions as &$question){

添加& 将使 $ questions 保持更新.但我想说,尽管推荐的时间较短,但还是建议使用第一个(请参阅Paystey的评论)

Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)

PHP foreach 文档:

为了能够直接在循环内修改数组元素,在$ value之前加上&.在这种情况下,该值将通过引用分配.

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.