PHP - 修改foreach循环当前对象 [英] PHP - Modify current object in foreach loop

查看:411
本文介绍了PHP - 修改foreach循环当前对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有可能编辑一个正在一个的foreach 循环内处理当前对象

我与对象 $问题的数组工作,我想通过,并期待与我的数据库这个问题对象关联的答案。因此,对于每一个问题去获取答案对象,并更新当前的 $问题 我的的foreach 循环,这样我可以输出/过程在其他地方。

 的foreach($问题为$问题){
    $的问题['答案'] = $ answers_model-> get_answers_by_question_id($问题['question_id']);
}


解决方案

有这样做的2种方式。

 的foreach($问题为重点$ = GT; $问题){
        $问题[$关键] ['答案'] = $ answers_model-> get_answers_by_question_id($问题['question_id']);
    }

这样,您保存密钥,这样你就可以在主 $问题再次更新变量

 的foreach($问题为&放大器; $问题){

添加&安培; 将保持 $问题更新。但我要说的第一个建议,即使这是短(见Paystey评论)

PHP 的foreach 文件:


  

为了能够直接修改环路precede $值内的数组元素与&放大器;.在这种情况下,该值将通过参照被分配


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

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

解决方案

There are 2 ways of doing this

   foreach($questions as $key => $question){
        $questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
    }

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

or

foreach($questions as &$question){

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)

Per 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循环当前对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆