PHP - 在 foreach 循环中修改当前对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10121483/
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
PHP - Modify current object in foreach loop
提问by Garbit
I was wondering if it is possible to edit the current object that's being handled within a foreachloop
我想知道是否可以编辑foreach循环内正在处理的当前对象
I'm working with an array of objects $questionsand 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 $questioninsidemy foreachloop so I can output/process elsewhere.
我正在处理一组对象$questions,我想通过并在我的数据库中查找与该问题对象相关的答案。因此,对于每一个问题去获取答案对象,并更新当前$question里面我的foreach循环,这样我可以输出/别处过程。
foreach($questions as $question){
$question['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
回答by Rene Pot
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 $questionsvariable
这样你就可以保存密钥,这样你就可以在主$questions变量中再次更新它
or
或者
foreach($questions as &$question){
Adding the &will keep the $questionsupdated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)
添加&将保持$questions更新。但我会说第一个是推荐的,即使它更短(见 Paystey 的评论)
Per the PHP foreachdocumentation:
根据PHPforeach文档:
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.
为了能够在循环内直接修改数组元素,在 $value 前面加上 &。在这种情况下,该值将通过引用分配。
回答by MrMesees
Surely using array_mapand if using a container implementing ArrayAccessto derive objects is just a smarter, semantic way to go about this?
当然array_map,如果使用容器实现ArrayAccess派生对象只是一种更智能的语义方式来解决这个问题?
Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.
数组映射语义在我见过的大多数语言和实现中都是相似的。它旨在根据输入数组元素返回修改后的数组(高级忽略语言编译/运行时类型首选项);循环旨在执行更多逻辑。
For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN()clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->waitcycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.
对于通过 ID / PK 检索对象,取决于您是否使用 SQL(似乎建议),我将使用过滤器来确保获得有效 PK 的数组,然后用逗号内爆并放入 SQLIN()子句中返回结果集。它通过 SQL 进行一次调用而不是多次调用,从而优化了一点call->wait循环。最重要的是,我的代码对于具有一定能力的任何语言的人来说都可以很好地阅读,而且我们不会遇到可变性问题。
<?php
$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);
vs
对比
<?php
$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
$arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);
If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arryou could always $arr = array_mapand be explicit.
如果你知道你在做什么,就永远不会有可变性问题(请记住,如果你打算覆盖,$arr你可以总是$arr = array_map明确的。

