I’m trying to output a multidimensional array as an HTML table with all possible combinations.
$attributes = [
'size' => [
'large',
'medium',
'small',
],
'color' => [
'red',
'blue',
'green',
],
'material' => [
'cotton',
'polyester',
],
];
The output needs to be:
size | color | material |
---|---|---|
large | red | cotton |
large | red | polyester |
large | blue | cotton |
etc. | etc. | etc. |
At any point, this array could receive new sizes, colors, materials or a whole new attribute.
Thus far, I’ve checked various other questions, and I can’t find any that doesn’t specify that the multidimensional array has a fixed amount of columns.
2
Answers
First, the easy part – outputting the table header:
Then construct an output array
$rows
that will contain the Caretesian product of the lists. We build this up from right-to-left, in order to match your desired output – so we start with the variations of the rightmost set, then duplicate this and prepend the value of the next column leftwards, and so on, until we have parsed all the headings:Then output the
$rows
array:This question is effectively a two-part duplicate of previously posted content on Stack Overflow. While Rob’s answer is implementing the general best-practice of html encoding characters when printing, none of the sample data needs this protective step.
Code: (Demo)
Or to sort the output rows by size, then color, then material, Titus’s generator will suffice.
Code: (Demo)