[英]PHP - Changing a value from a query result using foreach
I have a result from a SQL query stored inside $assignmentsViewList: 我有一个存储在$ assignmentsViewList内的SQL查询的结果:
Array
(
[0] => Array
(
[assign_id] => 302
[ClassCount] => 25
)
[1] => Array
(
[assign_id] => 303
[ClassCount] => 25
)
[2] => Array
(
[assign_id] => 325
[ClassCount] => 25
)
)
When I use it inside a foreach to change the value of ClassCount: 当我在foreach中使用它更改ClassCount的值时:
foreach ($assignmentsViewList as $task) {
$task['ClassCount'] = 2;
}
It doesn't work. 没用 But if I try this: 但是,如果我尝试这样做:
$assignmentsViewList[0]['ClassCount']=2;
The code works well. 该代码运行良好。 But I need it to work inside the foreach loop. 但是我需要它在foreach循环内工作。
In order to be able to directly modify array elements within the loop precede $task with &. 为了能够在循环内直接修改数组元素,在$ task之前加上&。 In that case the value will be assigned by reference. 在这种情况下,该值将通过引用分配。
Reference: PHP foreach() 参考: PHP foreach()
Try this: 尝试这个:
foreach ($assignmentsViewList as &$task) {
$task['ClassCount'] = 2; /* It will overwrite all 'ClassCount' values to 2 */
}
use &
. use &
。
Its means iterated over references to actual values of array &$task
它的意思是遍历对数组&$task
实际值的引用
foreach ($assignmentsViewList as &$task)
{
$task['ClassCount'] = 2; values of array
}
without & means its iterated over copy of array value.so its not overwrite your array. 不带&表示其迭代数组值的副本。因此,它不会覆盖您的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.