我正在woocommerce网站上工作,我需要找到一种方法来对optgroup中的选择选项进行分组。
我的选项以数组形式存储
aray = [
"A4 1.9tdi (2003-2009)",
"A4 2.0tdi (2003-2009)",
"Passat B7 1.9tdi(2003-2009)",
"Passat B7 2.0 tdi(2003-2010)"
]
我不需要通过php进行选择,该选择将通过使用字符串将第一个空格分组到optgroup中的选项
通过使用功能
explode(' ',$s, 2) or by strpos($inputString, ' ');
我可以根据需要拆分值。
我需要修改当前用于显示选项的代码:
$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;
所以我可以显示按optgroup分组的选项,例如:
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)
如果有人可以帮助我,我将不胜感激。
我不确定我是否理解您的html部分。 (至少很难在手机上阅读)但这可能会满足您的要求,只需替换占位符html标签即可。
我首先创建一个新数组,该数组与第一个单词(汽车模型)相关。这也可以确保在我开始输出时将其排序。
然后我只输出键并内插子数组中的所有值。
$array = [
"A4 1.9tdi (2003-2009)",
"A4 2.0tdi (2003-2009)",
"Passat B7 1.9tdi(2003-2009)",
"Passat B7 2.0 tdi(2003-2010)"
];
foreach($array as $val){
$temp = explode(" ", $val);
$new[$temp[0]][] = $val;
}
foreach($new as $car => $cars){
echo "<some html tag>". $car . "</Some html tag>\n";
echo "<some other tag>" . implode("</some other tag>\n<some other tag>", $cars) . "</some other tag>\n";
echo "\n";
}
输出:
<some html tag>A4</Some html tag>
<some other tag>A4 1.9tdi (2003-2009)</some other tag>
<some other tag>A4 2.0tdi (2003-2009)</some other tag>
<some html tag>Passat</Some html tag>
<some other tag>Passat B7 1.9tdi(2003-2009)</some other tag>
<some other tag>Passat B7 2.0 tdi(2003-2010)</some other tag>
此格式格式化为选项组,将值放置在每个选项的value
attr中。<option value="1.9tdi (2003-2009)">
并将其全部包装在选择标签中。
$cars = array(
"A4 1.9tdi (2003-2009)",
"A4 2.0tdi (2003-2009)",
"Passat B7 1.9tdi(2003-2009)",
"Passat B7 2.0 tdi(2003-2010)"
);
foreach($cars as $car){
$model = explode(' ', $car, 2);
$make[$model[0]][] = $car;
}
$stmt = 'Select a car: <select id="cars">';
foreach($make as $label => $type){
$stmt .= '<optgroup label="'.$label.'">';
foreach($type as $car){
list($mk, $cr) = explode(' ', $car, 2);
$stmt .= '<option value="'.$cr.'">'.$cr.'</option>';
}
$stmt .= '</optgroup>';
}
$stmt .= '</select>';
在html中回显$ stmt变量。
<?=$stmt?>