在 foreach 循环中修改数组值

问题描述:

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

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

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

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 文档:

Per the PHP foreach documentation:

为了能够在循环内直接修改数组元素,在 $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.