Reputation: 3392
I have an array and would like to convert that to the select box. You could find my solution below. But I have a problem with my lats option output html layout. Where is my problem and how can I solve this issue?
My code:
if (isset($product->options) && count($product->options)) {
$option_name = '';
foreach ($product->options as $option) {
if (trim($option_name) != trim($option->name)) {
echo '<select class="width-100" name="product[option][name]['.$option->name.']">';
}
echo '<option value="'.$option->value.'">'.$option->value.'</option>';
if (trim($option_name) != trim($option->name)) {
echo '</select>';
}
$option_name = $option->name;
}
}
My output looks like:
<select class="width-100" name="product[option][name][Color]">
<option value="Black">Black</option>
</select>
<select class="width-100" name="product[option][name][Size]">
<option value="XL">XL</option>
</select>
<option value="X">X</option>
My array:
[options] => Array
(
[0] => stdClass Object
(
[name] => Color
[value] => Black
[price] => +50
[order] =>
)
[1] => stdClass Object
(
[name] => Size
[value] => XL
[price] => +10
[order] =>
)
[2] => stdClass Object
(
[name] => Size
[value] => X
[price] => +5
[order] =>
)
)
Upvotes: 0
Views: 1060
Reputation: 4591
Try this:
if (isset($product->options) && count($product->options)) {
$arr = [];
foreach ($product->options as $option) {
$arr[$option->name][] = '<option value="'.$option->value.'">'.$option->value.'</option>';
}
foreach ($arr as $k=>$v) {
echo '<select class="width-100" name="product[option][name]['.$k.']">';
echo join("\n", $v);
echo '</select>';
}
}
Upvotes: 1
Reputation: 507
Please try this
if (isset($product->options) && count($product->options)) {
$option_name = '';
$i = 0;
foreach ($product->options as $option) {
if (trim($option_name) != trim($option->name)) {
echo '<select class="width-100" name="'.$option->name.'">';
}
echo '<option value="'.$option->value.'">'.$option->value.'</option>';
if (trim($option_name) != trim($option->name)) {
echo '</select>';
}
$option_name = $option->name;
$i++;
}
}
Upvotes: 0