为什么我在以下场景中没有将数组值作为选择控件中的选项?

时间:2014-04-26 12:41:08

标签: php arrays html-select

我的标题为$volume_unit_list的数组如下:

Array
(
    [0] => Array
        (
            [id] => 5
            [unit] => Microsecond
            [created_at] => 1397479783
            [updated_at] => 1397479783
        )

    [1] => Array
        (
            [id] => 7
            [unit] => oz
            [created_at] => 1397548900
            [updated_at] => 1397672502
        )

    [2] => Array
        (
            [id] => 9
            [unit] => ml
            [created_at] => 1397641838
            [updated_at] => 1397672480
        )

    [3] => Array
        (
            [id] => 10
            [unit] => L
            [created_at] => 1397672517
            [updated_at] => 1397672517
        )

    [4] => Array
        (
            [id] => 12
            [unit] => gms
            [created_at] => 1398196412
            [updated_at] => 1398196412
        )

)

显示数组值的选择代码如下:

echo "<tr id='reb$rebate_no'>
        <td>
           <input type='text' name='pack[]' value='' class='form-control' size='8'/>
        <td>
        <div class='btn-group'>
        <select id='unit' name='units[]' class='form-control'>
           <option value=''  if $data.id=='' selected='selected'{/if}>Select Unit</option>
           foreach ($volume_unit_list as $key=>$value)
             <option value=$key[id]>$key[unit]</option>
        </select>
        </div>
        </td>
      </tr>";

有人可以纠正我在选择控件中显示数组值时所犯的错误吗?

1 个答案:

答案 0 :(得分:0)

如果以更易读的方式编写代码,您将更容易看到错误。

如果foreach循环位于带引号的文字中,则无法执行。您需要终止字符串,然后运行循环,然后完成字符串。

echo "<tr id='reb$rebate_no'>
        <td>
           <input type='text' name='pack[]' value='' class='form-control' size='8'/>
<-- Missing </td> -->
        <td>
        <div class='btn-group'>
        <select id='unit' name='units[]' class='form-control'>
           <option value=''  if $data.id=='' selected='selected'{/if}>Select Unit</option>";

<?php
    foreach ($volume_unit_list as $key=>$value) {
        echo '<option value="' . $key['id'] . '">' . $key['unit'] . '</option>';
    }
?>
echo "</select>
        </div>
        </td>
      </tr>";