【问题标题】:Display array list elements in dropdown list in php在php的下拉列表中显示数组列表元素
【发布时间】:2017-08-17 08:35:52
【问题描述】:

例如,我有这样的数组:

$someArray = Array (
    [stationList] => Array (
        [0] => Array (
            [stationName] => A.S.Peta Bypass
            [stationId] => -1 )
        [1] => Array (
            [stationName] => Aala
            [stationId] => -1 )
    )
)

现在你想在 php 的下拉列表中显示数组元素(stationName),我使用了以下代码:

<select id="txtLabourId">                                                                                                                          
  <option selected="selected">Choose one</option>

  <?php
    foreach($someArray as $name) { ?>
      <option value="<?php echo $name['stationName'] ?>"><?php echo $name['stationName'] ?></option>
  <?php
    } ?>                                                                                                              
</select>   

但它给出了错误:

Undefined index stationName on line 222

如何解决这个问题?任何帮助表示赞赏。

【问题讨论】:

  • 先用stationList检查

标签: php arrays dropdown


【解决方案1】:

$someArray 数组包含另一个数组,所以像这样从内部数组开始你的 foreach 循环

<?php
    foreach($someArray['stationList'] as $station) { 
?>
      <option value="<?php echo $station['stationId'] ?>"><?php echo $station['stationName'] ?></option>
<?php
    } 
?>   

【讨论】:

    【解决方案2】:

    您应该将内部数组stationList 添加到循环中。

    你的循环代码应该是这样的:

    foreach($someArray['stationList'] as $name)
    

    【讨论】:

      【解决方案3】:

      您需要将stationList 提供给您的foreach,而不是包装数组,所以:

      foreach($someArray['stationList'] as $name) { ...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-05
        • 2013-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-25
        • 2013-05-28
        • 1970-01-01
        相关资源
        最近更新 更多