gpt4 book ai didi

php - 数组在不进行操作的情况下发生奇怪的变化

转载 作者:行者123 更新时间:2023-12-03 04:40:55 25 4
gpt4 key购买 nike

我面临着一种非常奇怪的行为。我有 $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);

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

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

debug($stats['answer_styles']);
foreach($answer_styles as $answer_style){
debug($stats['answer_styles']);
...

问题是第一个调试显示了它应该显示的数据,但第二个调试显示了被第一个调试覆盖的最后一条记录(因此,从 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
)

)

最佳答案

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

做:

unset($answer_style);

第一次循环之后,事情就会得到解决。

关于php - 数组在不进行操作的情况下发生奇怪的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8328082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com