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 inside the repetition loop, instead of mounting an array, create a conditional to concatenate a string until you get to the expected result.
If we follow with the example above, from the end result we can make another loop
foreach ($rs as $k => $v) {
echo $k.' '.implode(',', $v);
}
/**
Resultado
M1 c1,c2,c3,c4
M2 c1
*/
Observing:
The example is purely didactic. It is possible to reduce and mount the string directly in the first loop of repetition foreach ()
.
Data modeling
When it comes to a problem of this kind, it’s 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 as you can avoid that kind of "gambiarra" and other difficulties you will have in the future.
Ever tried to blow up?
– user28595
yes more I am not knowing to group
– Fabio Henrique
$id2 is an array or string like this right there?
– user28595
This is database work. Don’t do this with PHP. Use pivoting (SQL PIVOT TABLE) and you will achieve the same result more elegantly.
– StillBuggin