I am working on a woocommerce site and I need to find a way to group select options in optgroups.
My option are stored as array like
aray = [
"A4 1.9tdi (2003-2009)",
"A4 2.0tdi (2003-2009)",
"Passat B7 1.9tdi(2003-2009)",
"Passat B7 2.0 tdi(2003-2010)"
]
No what I need is to make by php a select that would group the options in optgroup by using the string up to first space
By using the function
explode(' ',$s, 2) or by strpos($inputString, ' ');
I can split the values as required.
I need to adapt the code that I am currently using for showing options:
$html = '<span class="number">' . ($level + 1).'</span><select class="'.$class.'" name="'.$levelData['url_parameter'].'" '.$extra.'>;
foreach ( $this->getLevelOptions($level) as $val ){
$html .= '<option value="'.esc_attr( $val ).'" '.($val == $value ? 'selected' : '').'>'.esc_html( $val ).'</option>';
}
$html .= '</select>';
return $html;
So I can show the options grouped by optgroup like:
A4 (optgroup)
A4 1.9tdi (2003-2009)
A4 2.0tdi (2003-2009)
Passat (optgroup)
Passat B7 1.9tdi(2003-2009)
Passat B7 2.0 tdi(2003-2010)
I would appreciate if someone could help me.
2
Answers
I’m not sure I understand your html part. (It’s very hard to read on mobile at least)
But this will probably do what you want, just replace the placeholder html tags.
I first create a new array which is associative on the first word (car model).
This also ensures that it’s sorted when I start outputting.
Then I just output the key and implode all values in the subarray.
Outputs:
https://3v4l.org/N8YTu
This formats to option group placing the values in the
value
attr within each option.<option value="1.9tdi (2003-2009)">
and wraps it all in a select tag.In html echo out your $stmt variable.
https://3v4l.org/bb2nR