How to group and list repeated values in array?

1

As shown below, in the database comes a list of seats bought, linked to their respective tables. How can I list by grouping the tables?

 [M] Significa => Mesa   [c] Significa  Cadeiras     

 $id2 = 'M1-c1, M1-c2, M1-c3, M1-c4, M2-c1'; // Como vem do banco

  echo M1 // como gostaria 
  echo M2 // como gostaria 

  echo M1  c1,c2,c3 // ou se fosse possível
  echo M2  c1 
    
asked by anonymous 17.01.2016 / 15:16

1 answer

4

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.

    
17.01.2016 / 15:39