【问题标题】:in php create a selection in option list from csv file在 php 中从 csv 文件的选项列表中创建一个选择
【发布时间】:2018-05-19 06:36:54
【问题描述】:

我有一个创建选择选项列表的 csv 文件。

提交后选择的选项被操作系统清除。我怎样才能将选项保留在选择中?

CSV 文件:

"Agusta Westland 109s",A109,2,Turbine,IFR,7,155,4,250,2500
"Bell 427",B427,2,Turbine,VFR,7,140,5,200,2000
"Eurocopter AS355 Ecureuil",Squirrel,2,Turbine,VFR,5,120,5,180,1800
"Eurocopter EC130 B4",EC130,1,Turbine,VFR,6,120,4,140,2500
"Robinson R22",R22,1,Piston,VFR,1,90,8,50,300
"Robinson R44 Raven 2",R44,1,Piston,VFR,3,110,6,75,1100

PHP 代码:

echo "<form method='post' action=''>";
if (!file_exists('types.csv')) {
    exit("Your Types file doesn't exist");
} else {
	$types = array_map('str_getcsv', file('types.csv'));
	$aircraftTitles = array("Aircraft");
	echo "<table class='table'>";
	echo "<tr>";
    foreach ($aircraftTitles as $row){ 	
    	echo "<th>".$row."</th>";
	}
	echo "</tr>";
	echo "<tr>";
	//select type 
	echo "<td><select name = 'type'>";
	echo "<option value='".null."'>Select Aircraft Type</option>";
    foreach ($types as $row){ 
    	echo "<option value='".$row[1].",".$row[6].",".$row[7].",".$row[8]."'>".$row[1]."</option>";
    }
    echo "</select></td>";
    echo "<tr>";
echo "</table>";
}

非常感谢您的帮助

【问题讨论】:

    标签: php csv select option selected


    【解决方案1】:

    您需要跨数组的值运行 $_POST 中的值。如果匹配,则选择作为选定选项。如果不匹配,则仅显示该选项。

    像这样:

    echo "<form method='post' action=''>";
    if (!file_exists('types.csv')) {
        exit("Your Types file doesn't exist");
    } else {
        $types = array_map('str_getcsv', file('types.csv'));
    
        $aircraftTitles = array("Aircraft");
        echo "<table class='table'>";
        echo "<tr>";
        foreach ($aircraftTitles as $row){
            echo "<th>".$row."</th>";
        }
        echo "</tr>";
        echo "<tr>";
        //select type
        echo "<td><select name = 'type'>";
        echo "<option value='" . null . "'>Select Aircraft Type</option>";
    
        foreach($types as $row) {
    
              $str = $row[1]. "," .$row[6] . "," . $row[7] . "," .$row[8];
              if($_POST['type'] == $str) {
    
                echo  '<option value="' . $str . '"' . ' selected="selected"' . '>' . $row[1] . '</option>';
    
              }else {
    
                echo  '<option value="' . $str . '">' . $row[1] . '</option>';
    
              }
    
         }
    
        echo "</select></td>";
        echo "<tr>";
    echo "</table>";
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-14
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 2020-03-21
      • 2013-06-13
      相关资源
      最近更新 更多