更改foreach循环内的值;t改变正在迭代的数组中的值


Changing value inside foreach loop doesn't change value in the array being iterated over

为什么会产生这样的结果:

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
)

我正在尝试获得101手机-产品目录TXT.TXT.gz

想一想发生了什么?

编辑:好吧,我找到了解决方案。。。数组中的变量有我看不到的值。。。进行

$output = preg_replace('/[^('x20-'x7F)]*/','', $output);
echo($output);

清理并使其正常工作

文档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
?>

只有当迭代数组可以被引用(即,如果它是一个变量)时,才可能引用$value。以下代码不起作用:

<?php
/** this won't work **/
foreach (array(1, 2, 3, 4) as &$value) {
    $value = $value * 2;
}
?>

尝试

foreach( $store as $key => $value){
    $store[$key] = $value.".txt.gz";
}

数组中的$value变量是临时的,它不引用数组中的条目
如果您想更改原始数组条目,请使用引用:

foreach ($store as $key => &$value) {
                       //  ^ reference
    $value .= '.txt.gz';
}

您正在重写循环中的值,而不是数组中的键引用。

尝试

 $store[$key] = $value.".txt.gz";

通过$value作为引用:

foreach( $store as $key => &$value){
   $value = $value.".txt.gz";
}

尝试

$catalog = array();
foreach( $store as $key => $value){
    $catalog[] = $value.".txt.gz";
}

print_r ($catalog);

foreach( $store as $key => $value){
    $store[$key] = $value.".txt.gz";
}

print_r ($store);

取决于您想要实现的

谢谢:)

我相信这就是你想要做的:

foreach( $store as $key => $value){
$store[$key] = $value.".txt.gz";
}
unset($value);
print_r ($store);

数组映射:怎么样

$func = function($value) { return $value . ".txt.gz"; };
print_r(array_map($func, $store));
foreach(array_container as & array_value)

是在foreach循环中修改数组元素值的方法。