gpt4 book ai didi

PHP范围问题

转载 作者:行者123 更新时间:2023-12-03 22:58:00 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com