【发布时间】:2016-10-25 21:19:05
【问题描述】:
代码如下:
if($condition == 'condition1' || $condition == 'condition2')
{
$found = false;
//loop through the array of customers contracts
foreach($cust_cont as $cust)
{
//if the customer is found
if ($cust["customer"] == $customer)
{
$temp = floatval($cust["hoursThisPer"]);
$temp += $time;
$cust["hoursThisPer"] = $temp;
$found = true;
}
}
if ($found == false)
{
$cust_cont[] = array("customer" => "$customer", "hoursUsed" => $hoursUsed,
"hoursAvail" => $allowed, "hoursThisPer" => (0 + $time));
}
}
所以,我要做的是遍历一个数组。如果数组确实有一个客户条目,我想将时间添加到该客户的使用时间。如果没有客户的条目,我想在我的数组中为该客户创建一个条目并初始化它的值。
数组的条目正在正确初始化,但是当我尝试更新它们时,发生了一些奇怪的事情。例如,如果我在数组中有 customer1,并且我想添加到 customer1 的 hoursThisPer,它会执行添加到该位置的动作。但是,下次需要更新时,customer1 的 hoursThisPer 设置为初始值,而不是更新后的值。我无法弄清楚我的逻辑中的缺陷。帮助将不胜感激。我有一些示例输出。
Customer1:0.25
time: 0.25
temp: 0.5
0.5
Customer1:0.25
time: 1.50
temp: 1.75
1.75
Customer1:0.25
time: 0.50
temp: 0.75
0.75
格式为Customer:初始时间;添加时间;初始时间 + 增加时间的预期总和; “更新”后的数组值;找到客户的下一个实例(并且循环继续)。
【问题讨论】:
-
添加 & 以更改 foreach 中的数组
foreach($cust_cont as &$cust) -
行得通!非常感谢!不过,我会说实话:我不知道为什么会这样。有什么方法可以告诉我它的作用和原因吗?
-
@dmcoding 变量前的
&符号使其成为通过引用传递。如果你不添加这个而不是$cust作为副本并且没有引用数组中的值。
标签: php arrays foreach associative-array boolean-logic