PHP范围问题

标签 php arrays scope

我试图查看一个记录数组(工作人员),在这个循环中,我调用一个函数,该函数返回另一个记录数组(每个工作人员的约会)。

foreach($staffmembers as $staffmember)
{   
        $staffmember['appointments'] = get_staffmember_appointments_for_day($staffmember);
        //  print_r($staffmember['appointments'] works fine 
}

这工作正常,但是,稍后在脚本中,我需要再次循环记录,这次使用约会数组,但它们不可用。

foreach ($staffmembers as $staffmember)
{                                                             
        //do some other stuff
        //print_r($staffmember['appointments'] no longer does anything
}

通常情况下,我会在第二个循环中执行第一个循环中的函数,但是这个循环已经嵌套在另外两个循环中,这将导致相同的 sql 查询运行 168 次。

有人可以建议解决方法吗?

如有任何建议,我们将不胜感激。

谢谢

最佳答案

foreach迭代数组的副本。如果要更改该值,需要reference它:

foreach($staffmembers as &$staffmember) // <-- note the &
{   
    $staffmember['appointments'] = get_staffmember_appointments_for_day($staffmember);
    //  print_r($staffmember['appointments'] works fine 
}

来自文档:

Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.

As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

关于PHP范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2880778/

相关文章:

javascript - 如何从 javascript 中的二维数组中删除开头的逗号?

javascript - 除非全局声明,否则无法从事件处理程序内的函数更新变量

scope - 使用 Drools 声明局部规则变量

javascript - 我无法让 JavaScript 事件监听器正常工作

php - 将字符串传递给 Javascript 函数不起作用

php - 只有响应的第一个元素可见 - php

java - 对对象数组进行快速排序

ios - 使用 Swift 将更多数据传递到 UISearchController

php - 转换 SQL 查询以与 PHP 形式一起使用(变量问题)

php - 使用 Yii 框架的安全问题