为什么这会产生这个:
foreach( $store as $key => $value){
$value = $value.".txt.gz";
}
unset($value);
print_r ($store);
Array
(
[1] => 101Phones - Product Catalog TXT
[2] => 1-800-FLORALS - Product Catalog 1
)
Run Code Online (Sandbox Code Playgroud)
我想获得101Phones - 产品目录TXT.txt.gz
关于最新情况的想法?
编辑:好吧,我找到了解决方案...我的数组中的变量具有我看不到的值......正在做
$output = preg_replace('/[^(\x20-\x7F)]*/','', $output);
echo($output);
Run Code Online (Sandbox Code Playgroud)
清理它并使其正常工作
Mic*_*hel 39
文档http://php.net/manual/en/control-structures.foreach.php清楚地说明了您遇到问题的原因:
"为了能够直接修改循环中的数组元素,在$ value之前加上&.在这种情况下,该值将通过引用分配."
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>
Run Code Online (Sandbox Code Playgroud)
只有在可以引用迭代数组时(即它是变量),才能引用$ value.以下代码不起作用:
<?php
/** this won't work **/
foreach (array(1, 2, 3, 4) as &$value) {
$value = $value * 2;
}
?>
Run Code Online (Sandbox Code Playgroud)
尝试
foreach( $store as $key => $value){
$store[$key] = $value.".txt.gz";
}
Run Code Online (Sandbox Code Playgroud)
$value数组中的变量是临时的,它不引用数组中的条目.
如果要更改原始数组条目,请使用引用:
foreach ($store as $key => &$value) {
// ^ reference
$value .= '.txt.gz';
}
Run Code Online (Sandbox Code Playgroud)
您正在重写循环内的值,而不是数组中的关键引用。
尝试
$store[$key] = $value.".txt.gz";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21546 次 |
| 最近记录: |