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

$numberは常に 1 になります (未定義の場合は何もありません)。配列をカウントする代わりに$number=0;、ループの前に設定してから使用します$number++;

于 2013-03-07T21:57:29.680 に答える
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 に答える