EDIT
Even when I didn't use a nested loop it produced duplicates. I finally made a dirty fix by setting the updates array key to the update key, so at least a duplicate would be overwritten... I swear it wasn't the data. The update ID is my primary key, so there's no way there's duplicates in the db, also I'm looking at my db right now and there's no duplicates.
Anyway, not a pretty solution, but I guess this solved it:
foreach( $L_a_updates as $update ){
if( array_key_exists($update['eventId'], $L_a_events) ){
$L_a_events[ $update['eventId'] ]['updates'][ $update['updateId'] ] = $update;
}
}
The answers below are good though, and clearly by more capable minds than mine at the moment. TGIF.
Original question below
It's a Friday afternoon, so it's probably something extremely dumb, but I can't get this to work properly.
I've got two arrays, $L_a_events
and $L_a_updates
. Every event can have 0 or more updates. I fetch the events from the db, then I fetch the updates, and then I run them through a loop to compare event IDs and add the updates to their events. So the final structure is something like:
Array(
[0] => Array(
['eventId'] => 2,
['message'] => 'Some message',
['updates'] => Array(
[0] => Array (
['updateId'] => 123,
['eventId'] => 2,
['message'] => 'Some update message',
)
)
)
);
I run this loop to achieve that:
foreach( $L_a_events as $key => $event ){
foreach( $L_a_updates as $update ){
if($update['eventId'] == $event['eventId']){
$L_a_events[$key]['updates'][] = $update;
}
}
}
Is something wrong with my loop?! The resultset from the database shows no duplicates. When I print both arrays before I run the loop, they both look fine.
It's only after this loop that for some reason a single update is added to an event array twice. Also, it doesn't do that with every update.
So after the loop, instead of the above array, I get this:
Array(
[0] => Array(
['eventId'] => 2,
['message'] => 'Some message',
['updates'] => Array(
[0] => Array (
['updateId'] => 123,
['eventId'] => 2,
['message'] => 'Some update message',
),
[1] => Array (
['updateId'] => 123,
['eventId'] => 2,
['message'] => 'Some update message',
)
)
)
);