我知道答案可能很简单,但很难让它发挥作用。我有以下代码
}
$csv = array();
// Open File with error handler
if (($file = fopen('./csv/file.csv', 'r')) === false) {
throw new Exception('There was an error loading the CSV file.');
}
else {
while (($line = fgetcsv($file, 1000)) !== false) {
$csv[] = $line;}
fclose($file);}
if (isset($_GET['names'])) {
$name = $_GET['names'];
$results = array();
foreach($csv as $curr) {
$Data = explode(',',$curr['1']);
if(in_array($names,$Data)
$results[] = $curr;
}
} else {
...... Blah blah blah
?>
所以我试图做的是解析来自url的数据,并使用get和search csv数组来查找每个键和数组[1](它的2列csv文件)中的匹配字符串,如果名称匹配则获取来自csv [0]的值并存储在数组中,因此我可以将其打印到屏幕上。因为我没有在我的数组中获得匹配的字符串而丢失了。我出错的任何帮助?
Csv文件的一个示例:
Charlie and the chocolate factory, Ronald Dahl
Hunger games, Suzanne Collins
ect
所以我想要做的是解析url中的数据?name = Suzanne,%20Collins来搜索我的csv数组。因此,它通过suzanne collins选取所有书籍并将值放在我的数组中。
答案 0 :(得分:0)
我尽可能地坚持使用尽可能多的代码,主要的变化是在寻找作者的循环中。正如我所提到的,fgetcsv
已经将字段拆分,但由于名称周围可能有空格(如示例所示),我在测试中使用了trim
以确保我没有丢失任何人。
// Open File with error handler
if (($file = fopen('./books.csv', 'r')) === false) {
throw new Exception('There was an error loading the CSV file.');
}
$books = array();
while (($line = fgetcsv($file)) !== false) {
$books[] = $line;
}
fclose($file);
if (isset($_GET['names'])) {
$name = $_GET['names'];
$results = array();
foreach($books as $book) {
if( $name == trim($book[1])) {
$results[] = $book;
}
}
print_r($results);
}
(请注意,我已根据测试目的更改了文件名,因此请不要忘记更改此内容)