使用Foreach循环更改Array中的变量Key值


Changing variable Key values in Array with a Foreach loop

foreach( $notZeroValue as $cardSetPosition => $timesChosen){
    echo $groupValue;
    $notZeroValue[$cardSetPosition + ($groupValue*100)] = $notZeroValue[$cardSetPosition];
    unset ($notZeroValue[$cardSetPosition]);
}

输出为0000(正确,因为$notZeroValue有四个元素,每个元素对应$groupValue = 0)

我知道一定有一个新手错误,因为将*100更改为+100会产生关键值101, 102, 103, 104

print_r($notZeroValue); //output = array()

$groupValue等于0你得到正确的结果,因为

$notZeroValue[$cardSetPosition + ($groupValue*100)] = $notZeroValue[$cardSetPosition];

$notZeroValue[$cardSetPosition] = $notZeroValue[$cardSetPosition];

用自身覆盖数组值。

然后从数组中删除元素。

所以最后数组将是空的

但是当你把*改成+$groupValue仍然在0:

$notZeroValue[$cardSetPosition + ($groupValue+100)] = $notZeroValue[$cardSetPosition];

将不会覆盖数组值,相反,您将创建新的键/值对,其中键比旧键多100。接下来,从数组中删除旧的键/值。最后你有4个新的键/值对