PHP从数组列表中选择选项

时间:2016-04-07 02:30:35

标签: php html

我是PHP新手,我尝试了几个小时,我想将数组项目显示给选择选项。这是代码:

<select name="state">
         <?php
          $arrstate=array
          (
             array("AK","Alaska"),
             array("AL","Alabama"),
             array("AR","Arkansas"),
             array("AZ","Arizona"),
             array("CA","California"),
             array("CO","Colorado"),
             array("CT","Connecticut"),
             array("DC","District of Columbia"),
             array("DE","Delaware"),
             array("FL","Florida"),
             array("GA","Georgia"),
             array("HI","Hawaii"),
             array("IA","Iowa"),
             array("ID","Idaho"),
             array("IL","Illinois"),
             array("IN","Indiana"),
             array("KS","Kansas"),
             array("KY","Kentucky"),       
          );
          for($lop=0;$lop<=49;$lop++)
              {
                if (strtoupper($lead_info['state'])==$arrstate[$lop][0])
              {
                echo "<option selected=\"selected\" value=\"".$arrstate[$lop][0]."\">".$arrstate[$lop][1]."</option>\n";           
              }else{
              echo "<option value=\"".$arrstate[$lop][0]."\">".$arrstate[$lop][1]."</option>\n";           
              }
              }
          ?>
        </select>

但它似乎只显示".$arrstate[$lop][1]." 什么似乎是问题?

3 个答案:

答案 0 :(得分:2)

试试吧

<?php
  $arrstate = array
  (
     'AK' => 'Alaska',
     'AL' => 'Alabama',
     'AR' => 'Arkansas',
     'AZ' => 'Arizona'   
  ); ?>
<select>
     <?php foreach($arrstate as $key => $value) { ?>
      <option value="<?php echo $key; ?>"  <?=($value == $current_zip_entered ? "selected" : "" )?>><?php echo $value; ?></option>
     <?php } ?></select>

答案 1 :(得分:0)

  <?php
      $arrstate=array
      (
         "AK","Alaska",
         "AL","Alabama",
         "AR","Arkansas",
         "AZ","Arizona"   
      );
   ?>

这是最简单的方法......

   <select>
         <?php
           foreach($arrstate as $key => $value) {
         ?>
          <option value="<?php echo $key; ?>"  <?=($value == $current_zip_entered ? "selected" : "" )?>><?php echo $value; ?></option>
         <?php
           }
          ?>
   </select>

答案 2 :(得分:0)

您可以像以下示例一样从数据库中检索:

      <select>
         <?php $result = mysqli_query($conn, "SELECT * FROM categories");
              while ($row = mysqli_fetch_array($result)) {                                
                    $categories = array($row["category"]);
                    $arrlength = count($categories);

                    for($x = 0; $x < $arrlength; $x++) {
                       echo  "<option>";
                       echo  $categories[$x]; 
                       echo  "</option>";
                                         }}?>
               </select>