0

我的问题是我不知道如何计算已过滤并从 CSV 文件输出的数据行。

我想做一些类似的事情:

$author = $_GET['author'];

$booklist = array();
$title1 = 'Harry Potter and the Deathly Hallows';
array_push($booklist, $title1);
$title2 = 'Harry Potter and the Goblet of Fire';
array_push($booklist, $title2);
$title3 = 'Harry Potter and the Prisoner of Azkaban';
array_push($booklist, $title3);

if (strtolower($author) == strtolower('J.K. Rowling')){
    echo '<h1>', ucwords($author), '</h1>';
    echo "<p>" . $title1 . "</p>";
    echo "<p>" . $title2 . "</p>";
    echo "<p>" . $title3 . "</p>";
    $number = count($booklist);
    echo "<p>We have $number of $author 's books.</p>";
}

哪个会输出;

J.K. Rowling
Harry Potter and the Deathly Hallows
Harry Potter and the Goblet of Fire
Harry Potter and the Prisoner of Azkaban
We have 3 of J.K. Rowling 's books.

但是,我的问题是,我的值来自 CSV 文件,并且正在输出的数据已被 IF 语句过滤。

CSV 文件包含以下值:

name,author,isbn,price
name,author,isbn,price
name,author,isbn,price
name,author,isbn,price

到目前为止,我管理的内容如下:

<?php
$author = $_GET['author'];

echo '<h1>', ucwords($author), '</h1>';
echo '<table border=1>'; //start table
$handle = fopen("books.csv", "r");

while (($books = fgetcsv($handle)) !== FALSE) {  
    list($bookname, $bookauthor, $bookisbn, $bookprice) = $books;

    if (strtolower ($author)==strtolower($bookauthor)) {
        $booklist = array();
        array_push($booklist, $bookname);
        $number = count($booklist);
        echo '<tr><td>',$bookname, //names
        '</td><td>',$bookauthor, //authors
        '</td><td>',$bookisbn, //ISBN
        '</td><td>',$bookprice, //price
        '</td></tr>';
    }
}
fclose($handle);
echo '</table>'; //end table
echo '<p> There are ', $number, ' books by this author. </p>';
?>

我的输出是:

J.K. Rowling
title1, J.K. Rowling, ISBN, Price
title2, J.K. Rowling, ISBN, Price
title3, J.K. Rowling, ISBN, Price
There are 1 books by this author. 

好像不算。

我不是 PHP 方面的佼佼者,因此我们将不胜感激。

4

3 回答 3

0

$booklist每次都通过循环重新声明。将它移到循环之外,你应该会很好。

$booklist = array(); //move here
while (($books = fgetcsv($handle)) !== FALSE) {  
list($bookname, $bookauthor, $bookisbn, $bookprice) = $books;

if (strtolower ($author)==strtolower($bookauthor))
 {
   array_push($booklist, $bookname);
   $number = count($booklist);
   echo '<tr><td>',$bookname, //names
   '</td><td>',$bookauthor, //authors
   '</td><td>',$bookisbn, //ISBN
   '</td><td>',$bookprice, //price
   '</td></tr>';
}
}
于 2013-03-07T21:56:26.257 回答
0

尝试移动以下行;

$booklist = array();

到 while 循环之上

于 2013-03-07T21:56:53.683 回答
0

$number总是为 1(或未定义,没有)。而不是计算数组,$number=0;在循环之前设置然后使用$number++;

于 2013-03-07T21:57:29.680 回答