Mid afternoon mental block. Simple PHP script to generate an HTML snippet. Will appreciate a second pair of eyes to spot what I’m doing wrong …
<?php $prevname = ''; ?>
<?php foreach($subcategories as $sub_category): ?>
<?php $newname = $sub_category->getCategory()->getName(); ?>
<?php $group_changed = strcmp($newname, $prevname); ?>
<?php if ($group_changed): ?>
<optgroup label="<?php echo $newname; ?>">
<?php endif; ?>
<option value="<?php echo $sub_category->getId(); ?>"><?php echo $sub_category; ?></option>
<?php if ($group_changed): ?>
</optgroup>
<?php endif; ?>
<?php endforeach; ?>
[Edit]
Generated HTML looks like this:
<select>
<optgroup label="Group1">
<option value="1">Group1 Sub Item 1</option>
</optgroup>
<optgroup label="Group1">
<option value="2">Group1 sub Item 2</option>
</optgroup>
<!-- and so on ...
</select>
instead of what I expected:
<select>
<optgroup label="Group1">
<option value="1">Group1 Sub Item 1</option>
<option value="2">Group1 sub Item 2</option>
</optgroup>
<optgroup label="Group2">
<option value="1">Group2 Sub Item 1</option>
<option value="2">Group2 sub Item 2</option>
</optgroup>
<!-- and so on ...
</select>
And you are not assigning $prevname to the $newname.
Additionally, the optgroup should be closed not in the same iteration, but on next optgroup name change. The code should look something like this: