Example with arrays:
$id2 = 'M1-c1, M1-c2, M1-c3, M1-c4, M2-c1';
$arr = explode(', ', $id2);
foreach ($arr as $v) {
$rs[substr($v, 0, 2)][] = substr($v, 3);
}
// Imprime o array (para teste)
print_r($rs);
/**
Resulta nisso
Array
(
[M1] => Array
(
[0] => c1
[1] => c2
[2] => c3
[3] => c4
)
[M2] => Array
(
[0] => c1
)
)
*/
To get to this result, you can manipulate the final array or even within the loop repetition, instead of assembling an array, create a conditional to concatenate a string until you get the result you expect.
If we follow the example above, from the final result we can make another loop of repetition
foreach ($rs as $k => $v) {
echo $k.' '.implode(',', $v);
}
/**
Resultado
M1 c1,c2,c3,c4
M2 c1
*/
Note:
The example is purely didactic. It is possible to reduce and assemble the string directly on the first loop%% re loop.
Data modeling
When it comes to such a problem, it is quite obvious that there is an inadequate problem or structure in data modeling. If you can, better structure the tables and columns of the database because you can avoid this type of "gambiarra" and other difficulties that will have in the future.