The most natural way would be to change your data structure a bit, so that the series
array is indexed by the row ID instead of an arbitrary running index. The would allow you to rewrite your loop to (using mysqli syntax as an example):
$stmt->bind_result($id, $country, $username, $subtotal);
$series = array();
while ( $stmt->fetch() ) {
$series[$id]['country'] = $country;
$series[$id]['data'][] = array(
'username' => $username,
'subtotal' => $subtotal,
);
}
which will give you a data structure like:
$series = array(
'hn' => array(
'country' => 'HN',
'data' => array(
0 => array(
'username' => 'GK_5',
'subtotal' => 86040
),
1 => array(
'username' => 'GK_8',
'subtotal' => 20358
),
// ...
)
),
// ...
);
If you need the data in the exact format shown in your post, you can of course loop over this array with foreach
to transform it, e.g.:
$rows = array();
foreach ( $series as $id => $record ) {
$record['id'] = $id;
$rows['series'][] = $record;
}