Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用Foreach循环更改数组中的变量键值_Php_Arrays_Foreach - Fatal编程技术网

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