I am currently using Wordpress to create and populate a <select>
with <option>
s.
<?php if( $lh_loop->have_posts() ): ?>
<select class="mousechoice left">
<?php while( $lh_loop->have_posts() ) : $lh_loop->the_post();?>
<optgroup label="<?php echo get_field("company_name") ?>">
<option data-id="<?php echo $post->post_name; ?>"><?php the_title(); ?></option>
</optgroup>
<?php endwhile; ?>
</select>
<?php endif; ?>
Which is showing this:
<select class="mousechoice left">
<optgroup label="SteelSeries">
<option data-id="sensei">Sensei</option>
</optgroup>
<optgroup label="Razer">
<option data-id="deathadder">Deathadder</option>
</optgroup>
<optgroup label="SteelSeries">
<option data-id="kana">Kana</option>
</optgroup>
</select>
I would like a way of grouping posts with the same company name into an <optgroup>
. Which would result in this:
<select class="mousechoice left">
<optgroup label="SteelSeries">
<option data-id="sensei">Sensei</option>
<option data-id="kana">Kana</option>
</optgroup>
<optgroup label="Razer">
<option data-id="deathadder">Deathadder</option>
</optgroup>
</select>
I have tried comparing the current post's company to the previous post's company but realised that a post with the same company name could be after or before another post with a different company name.
I know that I could also use if statements to specify each company name but I would like a solution that would allow for other company names not yet input into Wordpress.
If you want to group all the elements of an array by certain values, I like iterating over the array to collate it first and then doing the display in a separate loop.
So I would take each element and put them into an array that has the value I want to group on as a key.
So I want to create an array that looks like
['company A' =>[ [1 => 'option 1'],
[2 => 'option 2'],
...
],
'company B' =>[ [1 => 'option 3'],
[2 => 'option 4'],
...
],
...
]
To create this array you could use something like (untested)
$grouped = array();
while( $lh_loop->have_posts() ) :
$lh_loop->the_post();
$key = get_field("company_name")
$subkey = $post->post_name;
$display = the_title();
if (empty($grouped[$key]){ //if they key isn't set yet
//add the key to the array as a new element
$grouped[] = array($key=>array($subkey=>$title));
}else{
//else add to existing key
$grouped[$key][] = array($subkey=>$title);
}
endwhile;
Then, to display the list, do something like
foreach ($grouped as $comp => $group){
echo "<optgroup label=\"$comp\">";
foreach ($group as $key => $val){
echo "<option data-id=\"$key\">$val</option>";
}
echo "</optgroup>";
}