代码如下:
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,则会执行添加到该位置的 Action 。但是,下次需要更新时,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
格式为客户:初始时间;是时候添加了;初始时间+追加时间的预期总和; “更新”后数组的值;找到客户的下一个实例(并且循环继续)。
最佳答案
您需要通过引用获取数组,否则您只是更新一个名为 $cust
的新变量:
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));
}
}
这里,我在 foreach
循环中的 $cust
声明之前添加了一个 &
。在此情况下,$cust
不是一个具有当前 $cust_cont
元素值的新变量,而是对此元素的实际引用。
关于php - PHP 中数组临时更新,但不永久更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37993321/