php |将数组转换为选择框

时间:2015-02-13 09:54:57

标签: php arrays select

我有一个数组,想将其转换为选择框。你可以在下面找到我的解决方案但是我的lats选项输出html布局有问题。我的问题在哪里,我该如何解决这个问题?

我的代码:

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;       
            }
        } 

我的输出如下:

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

我的阵列:

 [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] => 
                )

        )

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:0)

请试试这个

   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++; 
        }
    }