繁体   English   中英

optgroup 中的 PHP 选项分组

[英]PHP grouping of options in optgroup

我正在一个 woocommerce 网站上工作,我需要找到一种方法来对 optgroups 中的选择选项进行分组。

我的选项存储为数组

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>

https://3v4l.org/N8YTu

此格式为选项组将值放置在每个选项内的value attr 中。 <option value="1.9tdi (2003-2009)">并将其全部包装在一个 select 标签中。

$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?>

https://3v4l.org/bb2nR

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM