PHP选项值建议来自平面文件

问题描述 投票:2回答:1

我怎样才能使这个表单显示$ data的第一列中的单词? 这是我正在尝试但不起作用。正如你所看到的,我无法让它与<option value>一起运行

<?php

$data = '
Naranja:Orange
Manzana:Apple
Tomate:Tomato
Zanahoria:Carrot
Lechuga:Lettuce
Plane:Avión';


if($data && !empty($_GET['word'])) {
    $line = explode("\n", $data);
    for($i = 0; $i<count($line); $i++) {
        $item = explode(":", $line[$i]);
        if($_GET['word'] == $item[0]) { echo"<div>" . $item[0] . "</div> <div>" . $item[1] . "</div>"; break; }
    }
}


else {echo '

<form>
<input type="text" name="word" list="spanishlist" autocomplete="off">
<datalist id="spanishlist">
<option value="' . $item[0] . '">
</datalist>
</form>

';
}
?>
php file flat-file
1个回答
0
投票
<?php

$data = 'Naranja:Orange
Manzana:Apple
Tomate:Tomato
Zanahoria:Carrot
Lechuga:Lettuce
Plane:Avión';

$pairs = explode("\n",$data);
$options = [];
$selected = '';
$html = '';
foreach($pairs as $pair) {
    $parts = explode(':', $pair);
    if (!empty($_GET['word']) && $_GET['word']==$parts[0]) {
        $html .= "<div>" . $parts[0] . "</div> <div>" . $parts[1] . "</div>";
    }
    $options [] = '<option value="' . $parts[0] . '">'; 
}
$html .= '<datalist id="fruits">';
$html .= implode($options);
$html .= '</datalist>';
$html .= '<input list="fruits">';

echo $html;
© www.soinside.com 2019 - 2024. All rights reserved.