Twig:将数组映射到表

I need to have such output

--------------------------------
|    | id1   | id2   | id  ... |
--------------------------------
| m1 | x1,x2 | x3    | x5      |
--------------------------------
| m2 | x4    | x6,x7 | ...     |
--------------------------------
|m...| ...   | ...   | ...     |
--------------------------------

where "x" is unique, "m" and "id" are not unique;

each row in object array returns m,x,id values

how can I map such array using other array to have above result?

main problem is to map first row as header and then make x'es to sort based on column header.

I know how to use nested loop in Twig but have no idea how to prepare array with data.

results from database can be sorted by any of this values if needed.