<?php
$string = file_get_contents("csv.csv");
$array = explode(",", $string);
$q = strtolower($_GET[q]);
foreach ($array as $value) {
$result = explode(":", $value);
if (strpos($q, $result[0]) !== false) {
$output = $result[1];
}
}
echo $output;
?>
这是我要转换成字符串的文件csv.csv
的内容。
hello: how are you doing,
hi: what are you,
df:df
如果$_GET[q]
(和$q
)为hello
,则$output
为how are you doing
。然而,如果它是hi
,我没有得到输出what are you
,或者如果我做df
,我没有得到df
。
为什么会发生这种情况?事先感谢您的帮助。
你被逗号爆炸了,但事实是你用逗号加换行符分隔每个值。
爆炸后,你的数组("你好"、"全民健康保险实施'…"、"' ndf:…"],这就是为什么没有匹配的字符串比较。
试
$array = explode(",'n", $string);
编辑:正如@Michael Berkowski所说,你也可以修改
参数if (strpos($q, trim($result[0])) !== false)
参数的顺序取决于您想要提供的部分匹配类型。根据您当前的参数顺序,参数"hi"将匹配"hi", "h"answers"i",但不匹配"high"。
如果你按照Michael的建议翻转它们,参数"hi"将匹配"hi"answers"high",但不匹配"h"或"i"。
使用str_getcsv代替手动解析CSV
使用str_getcsv并将$_GET[q]替换为$_GET['q']可以修复此问题
$csv = file_get_contents('csv.csv');
$array = str_getcsv($csv);
var_dump($array);
$q = $_GET['q'];
foreach ($array as $value) {
$result = explode(":", $value);
if (strpos($q, $result[0]) !== false) {
$output = $result[1];
}
}
echo $output;