[英]Cascading Dropdown CSV
我有一個表單,用戶可以從下拉列表中選擇課程,從下拉列表中選擇位置,然后在文本字段中手動填寫日期。
我需要讓用戶選擇路線和位置,並且用戶可以從可用日期列表中進行選擇。
我想使用CSV文件。 我真的別無選擇,因為我無法在網絡上使用本地數據庫。 這將每周從數據庫中生成兩次。
CSV文件僅包含課程,位置和日期。 例如:
Course Location Date
Dreamweaver Intro Minneapolis, MN 1/5/2015
Dreamweaver Intro Minneapolis, MN 3/5/2015
Dreamweaver Intro Minneapolis, MN 5/5/2015
Illustrator Intro Orlando, FL 3/5/2015
Illustrator Intro Orlando, FL 1/5/2015
Illustrator Intro Orlando, FL 5/5/2015
我對PHP很基礎,並且不確定從哪里開始。 我發現有關使用CSV文件進行級聯下拉菜單的信息很少。 任何幫助,將不勝感激。
我相信CSV文件如下
Dreamweaver Intro Minneapolis, MN, 5/5/2015
Illustrator Intro Orlando, FL, 3/5/2015
話雖如此,您可以閱讀每一行,然后以“,”將其展開。 它將導致像
array("Dreamweaver Intro Minneapolis", "MN", "3/5/2015");
創建三個數組-課程,位置和日期。 繼續將元素添加到單個列表中。
使用列表生成下拉列表。 示例代碼如下:
<?php
generateDropdownFromCsv(
"Course, Location, Date
Dreamweaver Intro Minneapolis, MN, 1/5/2015
Dreamweaver Intro Minneapolis, MN, 3/5/2015
Dreamweaver Intro Minneapolis, MN, 5/5/2015
Illustrator Intro Orlando, FL, 3/5/2015
Illustrator Intro Orlando, FL, 1/5/2015
Illustrator Intro Orlando, FL, 5/5/2015");
function generateDropdownFromCsv($fileContent){
$courses = array();
$locations = array();
$dates = array();
foreach( explode( "\n", $fileContent ) as $eachLine ){
$column = explode( ",", $eachLine );
array_push( $courses, $column[0] );
array_push( $locations, $column[1] );
array_push( $dates, $column[2] );
}
echo "<select>\n";
foreach( $courses as $course ){
echo "<option>" . trim($course) . "</option>\n";
}
echo "</select>\n";
echo "<select>\n";
foreach( $locations as $location ){
echo "<option>" . trim($location) . "</option>\n";
}
echo "</select>\n";
echo "<select>\n";
foreach( $dates as $date ){
echo "<option>" . trim($date) . "</option>\n";
}
echo "</select>\n";
}
?>
我們將使用該問題的答案逐行讀取您的CSV文件(使用fgets()
並且在while循環內,我們將收集如下所示的選項列表值數組:
<?php
$handle = fopen("path/to/your/inputfile.csv", "r");
$courses = array();
$locations = array();
$dates = array();
if ($handle) {
$l = 0;
while (($line = fgets($handle)) !== false) {
if ($l === 0){
//escaping the csv header line
$l++;
continue;
}
$options = explode("," $line);
$courses[] = trim($options[0]);
$locations[] = trim($options[1]);
$dates[] = trim($options[2]);
$l++;
}
} else {
echo "<h1>Error: Opening the file has been failed.</h1>";
}
fclose($handle);
?>
<!-- HTML and inside a form-->
<select name="courses">
<?php for ($i = 0; $i < count($courses); $i++): ?>
<option value="<?php echo $courses[$i]; ?>"><?php echo $courses[$i]; ?></option>
<?php endfor; ?>
</select>
<select name="locations">
<?php for ($i = 0; $i < count($courses); $i++): ?>
<option value="<?php echo $locations[$i]; ?>"><?php echo $locations[$i]; ?></option>
<?php endfor; ?>
</select>
<select name="dates">
<?php for ($i = 0; $i < count($courses); $i++): ?>
<option value="<?php echo $dates[$i]; ?>"><?php echo $dates[$i]; ?></option>
<?php endfor; ?>
</select>
注意
您必須檢查csv文件的有效性。 即,在開始處沒有特別的空行,並且每行有三個值,兩個逗號分隔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.