Php 使用Foreach循环更改数组中的变量键值
输出为Php 使用Foreach循环更改数组中的变量键值,php,arrays,foreach,Php,Arrays,Foreach,输出为0000(正确,因为$notZeroValue有四个元素,每个元素$groupValue=0) 我知道一定是新手出错了,因为将*100更改为+100会生成键值101,102,103,104 foreach( $notZeroValue as $cardSetPosition => $timesChosen){ echo $groupValue; $notZeroValue[$cardSetPosition + ($groupValue*100)] = $notZero
0000
(正确,因为$notZeroValue
有四个元素,每个元素$groupValue=0
)
我知道一定是新手出错了,因为将*100
更改为+100
会生成键值101
,102
,103
,104
foreach( $notZeroValue as $cardSetPosition => $timesChosen){
echo $groupValue;
$notZeroValue[$cardSetPosition + ($groupValue*100)] = $notZeroValue[$cardSetPosition];
unset ($notZeroValue[$cardSetPosition]);
}
当
$groupValue
等于0
时,您会得到正确的结果,因为
print_r($notZeroValue); //output = array()
变成
$notZeroValue[$cardSetPosition + ($groupValue*100)] = $notZeroValue[$cardSetPosition];
它正在用自身覆盖数组值
接下来从数组中删除元素
因此,在最后,数组将为空
但是当您将*
更改为+
并且$groupValue
仍处于0
时:
$notZeroValue[$cardSetPosition] = $notZeroValue[$cardSetPosition];
您将不会覆盖数组值,而是创建新的键/值对,其中键比旧键多100个。接下来从数组中删除旧的键/值。因此,最后您有4个新的键/值对。那么您遇到的问题是什么?我认为您必须提供更多信息。哪里定义了
$groupValue
?阵列是什么样子的?你得到的结果是什么?你期望的结果是什么?啊!我没有意识到!好的,当$groupValue==0时,我将添加一个if,谢谢!!
$notZeroValue[$cardSetPosition + ($groupValue+100)] = $notZeroValue[$cardSetPosition];