阵列暂时更新,但不会在 PHP 内永久更新

Array updating temporarily, but not updating permanently in PHP

代码如下:

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 

格式为客户:初始时间;时间添加;初始时间 + 添加时间的预期总和; "updated" 后数组的值;找到客户的下一个实例(并且循环继续)。

您需要通过引用获取您的数组,否则您只是在更新一个名为 $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 元素值的新变量,而是对该元素的实际引用。

默认情况下,在 foreach 循环中创建的变量(在本例中为 $cust)是按值创建的,而不是按引用创建的。 您可以将其更改为通过引用传递(通过前缀 &,如 splash58 在评论中所建议的那样),允许您通过更改创建的变量来更改原始数组:

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;
    }
}

或者你也可以获取相关索引,直接编辑数组;

foreach($cust_cont as $index => $cust)
{   
    //if the customer is found
    if ($cust["customer"] == $customer) 
    {
        $temp = floatval($cust["hoursThisPer"]);
        $temp += $time;
        $cust_cont[$index]["hoursThisPer"] = $temp;
        $found = true;
    }
}

就我个人而言,我发现很容易漏掉“&”,所以我更喜欢第二个选项,但我敢肯定这还远未达到普遍的看法。

如PHP手册所述:http://php.net/manual/en/control-structures.foreach.php

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.