Reputation: 17900
I am facing a very weird behaviour. I have the $answer_styles
array with some data, which I need to manipulate:
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);
and then I save it to another variable, for later use: $stats['answer_styles'] = $answer_styles;
Now, I need to step into the original array using a foreach
loop. I've done this:
debug($stats['answer_styles']);
foreach($answer_styles as $answer_style){
debug($stats['answer_styles']);
...
The problem is that the first debug shows the data it should show, but the second debug shows the last record overwritten by the first one (so, from 1, 2, 3, 4 it now shows 1, 2, 3, 1). Why is this happening since I don't manipulate the $stats
array, but the $answer_styles
one?
EDIT
This is the output for the first, respectively, the second debug:
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
)
)
Upvotes: 2
Views: 55
Reputation: 16951
This is because you are keeping reference to array element with this expression &$answer_style and using same variable name in second loop.
do:
unset($answer_style);
after first loop and things will be fixed.
Upvotes: 6