在我的PHP应用程序中查找错误时,我遇到了一些奇怪的行为。这是一个代码示例:
$x = array(array('t1' => 'a', 't2' => 'b', 't3' => 'c', 't4' => 'd', 't5' => 'e'),
array('t1' => 'a', 't2' => 'b', 't3' => 'c', 't4' => 'd', 't5' => 'e'),
array('t1' => 'a', 't2' => 'b', 't3' => 'c', 't4' => 'd', 't5' => 'e'),
array('t1' => 'a', 't2' => 'b', 't3' => 'c', 't4' => 'd', 't5' => 'e'));
$test = array();
$i = 0;
foreach ($x as $key => $value) {
$test[$i] = $value;
$test[$i]['t6'] = $i++;
}
print_r($test);
预期输出如下:
Array
(
[0] => Array
(
[t1] => a
[t2] => b
[t3] => c
[t4] => d
[t5] => e
[t6] => 0
)
[1] => Array
(
[t1] => a
[t2] => b
[t3] => c
[t4] => d
[t5] => e
[t6] => 1
)
[2] => Array
(
[t1] => a
[t2] => b
[t3] => c
[t4] => d
[t5] => e
[t6] => 2
)
[3] => Array
(
[t1] => a
[t2] => b
[t3] => c
[t4] => d
[t5] => e
[t6] => 3
)
)
我得到的是:
Array
(
[0] => Array
(
[t1] => a
[t2] => b
[t3] => c
[t4] => d
[t5] => e
)
[1] => Array
(
[t1] => a
[t2] => b
[t3] => c
[t4] => d
[t5] => e
)
[2] => Array
(
[t1] => a
[t2] => b
[t3] => c
[t4] => d
[t5] => e
)
[3] => Array
(
[t1] => a
[t2] => b
[t3] => c
[t4] => d
[t5] => e
)
[4] => Array
(
[t6] => 3
)
)
当我更改行
时$test[$i]['t6'] = $i++;
到
$test[$i]['t6'] = $i;
$i++;
它按预期工作。
我正在尝试了解问题的原因,所以我可以在类似的情况下避免它。有人可以解释为什么这里没有正确分配增量吗?
(顺便说一下,减量存在同样的问题。也许这是一个有用的信息和平。)
答案 0 :(得分:1)
您遇到语义错误,请尝试使用$ key而不是$ i
$x = array(array('t1' => 'a', 't2' => 'b', 't3' => 'c', 't4' => 'd', 't5' => 'e'),
array('t1' => 'a', 't2' => 'b', 't3' => 'c', 't4' => 'd', 't5' => 'e'),
array('t1' => 'a', 't2' => 'b', 't3' => 'c', 't4' => 'd', 't5' => 'e'),
array('t1' => 'a', 't2' => 'b', 't3' => 'c', 't4' => 'd', 't5' => 'e'));
$test = array();
$i = 0;
foreach ($x as $key => $value) {
$test[$key] = $value;
$test[$key]['t6'] = $i++;
}
print_r($test);
?>
答案 1 :(得分:0)
我最终自己找到了答案。分配似乎不起作用的原因是++和(数组)的运算符优先级是相同的,并且关联性是正确的。 (http://www.php.net/manual/en/language.operators.precedence.php)
这意味着$ i在用作数组键之前会递增。这意味着foreach循环的下一次迭代将覆盖行
中的相同键$test[$key] = $value;
唯一没有发生的事情是在循环的最后一次迭代中。
作为修复,我可以写
$test[$i++]['t6'] = $i;
看起来很奇怪,反直觉,或者我可以使用我的原始修复
$test[$i]['t6'] = $i;
$i++;
虽然不那么优雅,但更容易阅读。