dsgdhtr_43654 2014-04-10 17:47 采纳率: 100%
浏览 21
已采纳

由于引用变量引起的意外数据更改

This code is causing unexpected array content change. What could be the reason of this:

<?php

$arr[] = array('a', 'b');
$arr[] = array('c', 'd');

print_r($arr);
foreach ($arr as &$processed_arr) {

}

foreach ($arr as $processed_arr) {

}

print_r($arr);

Output:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => a
            [1] => b
        )

)
  • 写回答

1条回答 默认 最新

  • dongmei8511 2014-04-10 18:20
    关注

    It can indeed be due to your loop before. foreach in php leaves the iteration variable in scope even after the loop (Awful, I know).

    So code like this:

    $loop = [1,2,3];
    
    foreach ($loop as &$c) {}
    
    $c = 4;
    
    var_dump($loop);
    

    Will result in a loop variable containing [1,2,4]

    The rest of your code doesn't look like it could be the cause of this. Of course the implementation of status is free to do whatever but given the name it seems highly unlikely imo. :)

    Next time it might help to post more of the context. It's good to try to trim down the code posted like you have done, but if the posted code no longer exposes the problem (which yours does not) it makes it much harder to guess what's wrong.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100