Reputation: 6232
I'm having a weird problem where when I add elements to an array in PHP, the last element is added twice. For example, I create 3 arrays, but when I combine them using array_push()
or $array[]
, it duplicates the last element, giving me 4 arrays. Here's an example:
$master_array = [];
foreach($days as $i=>$day){
$single_array[$i] = array(
'id' => $day->id,
'some_variable' => $day->some_variable
);
$master_array[] = $single_array[$i];
}
$result = json_encode($master_array);
If desired output is [1,2],[2,3],[3,4]
, then it will echo [1,2],[2,3],[3,4],[3,4]
, duplicating the last element. Seems to be okay until I run the json_encode
. Any suggestions?
Upvotes: 0
Views: 392
Reputation: 2109
Why are you doing a multidimensional array for $single_array
? You don't need the extra dimension.
$master_array = array();
foreach($days as $i=>$day){
$single_array = array(
'id' => $day->id,
'some_variable' => $day->some_variable
);
$master_array[] = $single_array;
}
$result = json_encode($past_appts);
Upvotes: 1