<分区>
我正在编写 PHP 代码来对数组中的每个值进行一些转换,然后将一些值从外部源(MySQL 游标或另一个数组)添加到数组。如果我使用 foreach
和一个转换数组值的引用
<?php
$data = array('a','b','c');
foreach( $data as &$x )
$x = strtoupper($x);
$extradata = array('d','e','f');
// actually it was MySQL cursor
while( list($i,$x) = each($extradata) ) {
$data[] = strtoupper($x);
}
print_r($data);
?>
数据已损坏。所以我得到了
Array ( [0]=>A [1]=>B [2]=> [3]=>D [4]=>E [5] =>F )
代替
Array ( [0]=>A [1]=>B [2]=>C [3]=>D [4]=>E [5] =>F )
当我不使用引用而写
foreach( $data as &$x )
$x = strtoupper($x);
当然不会发生转换,但是数据也没有损坏,所以我明白了
Array ( [0]=>a [1]=>b [2]=>c [3]=>D [4]=>E [5] =>F )
如果我这样写代码
<?php
$result = array();
$data1 = array('a','b','c');
foreach( $data1 as $x )
$result[] = strtoupper($x);
$data2 = array('d','e','f');
// actually it was MySQL cursor
while( list($i,$x) = each($data2) ) {
$result[] = strtoupper($x);
}
print_r($result);
?>
一切都按预期进行。
Array ( [0]=>A [1]=>B [2]=>C [3]=>D [4]=>E [5] =>F )
当然,我复制数据就解决了问题。但是我想了解那个引用有什么奇怪的问题以及如何避免这些问题。也许在代码中使用 PHP 引用通常是不好的(就像许多人所说的 C 指针一样)?