phphtml-selectoptgroup

PHP grouping of options in optgroup


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.


Solution

  • 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.

    $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>';
    

    In html echo out your $stmt variable.

    <?=$stmt?>
    

    https://3v4l.org/bb2nR