How to group and list repeated values in array?

Asked

Viewed 1,367 times

1

As shown below, in the database comes a list of purchased chairs, linked to their respective tables. How can I list 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 
  • Ever tried to blow up?

  • yes more I am not knowing to group

  • $id2 is an array or string like this right there?

  • This is database work. Don’t do this with PHP. Use pivoting (SQL PIVOT TABLE) and you will achieve the same result more elegantly.

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 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.

  • Warning: implode(): Invalid Arguments passed in

  • Probably did something wrong, because in the example there is no way to give this error.

  • I did so $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); } foreach ($rs as $k => $k) { echo $k. ' '.implode(',', $v); }

  • What I must be doing wrong?

  • 1

    In his second foreach(), change foreach ($rs as $k => $k) for foreach ($rs as $k => $v)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.