数组奇怪地改变而不操纵它

lin*_*ndy 2 php arrays foreach

我面临一种非常奇怪的行为.我有$answer_styles一些数据,我需要操作:

foreach($answer_styles as $id => &$answer_style){
    $answer_style['id'] = $id;
    $answer_style_names[$id] = $answer_style['name'];
}
array_multisort($answer_style_names, SORT_ASC, SORT_STRING, $answer_styles);
Run Code Online (Sandbox Code Playgroud)

然后我将它保存到另一个变量,供以后使用: $stats['answer_styles'] = $answer_styles;

现在,我需要使用foreach循环进入原始数组.我这样做了:

debug($stats['answer_styles']);
foreach($answer_styles as $answer_style){
    debug($stats['answer_styles']);
        ...
Run Code Online (Sandbox Code Playgroud)

问题是第一个调试显示它应该显示的数据,但第二个调试显示第一个调试覆盖的最后一个记录(因此,从1,2,3,4现在显示1,2,3,1).为什么会发生这种情况,因为我没有操纵$stats数组,而是$answer_styles一个?

编辑

这是第一个,第二个调试的输出:

app/models/test.php (line 299)

Array
(
[0] => Array
    (
        [name] => Alege din 3
        [count] => 8
        [correct] => 2
        [id] => 3
    )

[1] => Array
    (
        [name] => Alege din 4
        [count] => 3
        [correct] => 2
        [id] => 2
    )

[2] => Array
    (
        [name] => Alege din 6
        [count] => 7
        [correct] => 3
        [id] => 4
    )

[3] => Array
    (
        [name] => Scrie raspunsul
        [count] => 2
        [correct] => 1
        [id] => 1
    )

)


app/models/test.php (line 301)

Array
(
[0] => Array
    (
        [name] => Alege din 3
        [count] => 8
        [correct] => 2
        [id] => 3
    )

[1] => Array
    (
        [name] => Alege din 4
        [count] => 3
        [correct] => 2
        [id] => 2
    )

[2] => Array
    (
        [name] => Alege din 6
        [count] => 7
        [correct] => 3
        [id] => 4
    )

[3] => Array
    (
        [name] => Alege din 3
        [count] => 8
        [correct] => 2
        [id] => 3
    )

)
Run Code Online (Sandbox Code Playgroud)

ios*_*seb 6

这是因为您使用此表达式&$ answer_style保持对数组元素的引用,并在第二个循环中使用相同的变量名称.

做:

unset($answer_style);
Run Code Online (Sandbox Code Playgroud)

在第一次循环后,事情将被修复.