我从w3school收集了这段代码,并对代码进行了一些更改。但现在stristr()并没有按我的意愿工作。例如,当我键入"E"时,结果显示5次"Eva",当我输入"Ev"时,显示3次"Eva"。需要注意的是,该数组有5个以"E"开头的单词和3个以"Ev"开头的词。另一个问题是,我如何将username保存为JSON文件中的数组元素,并在数据(username)中循环以获得搜索提示。这意味着我不想使用这样的硬编码数据,而是想使用动态数据进行搜索预测。
<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr( substr($name, 0, $len),$q)) {
if ($hint === "") {
$Name= stristr( substr($name,0),$q);
$hint =$Name;
} else {
$hint .= ", $Name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>
编辑:应该是$hint .= ", $name";
你可以改变你的循环,这样你就可以把找到的结果放在一个数组中:
<?php
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
$found = array();
foreach($a as $name) {
if (stristr( substr($name, 0, $len),$q)) {
array_push($found, $name);
}
}
print_r($found);
}
?>