2013-03-07 1 views
0

내 문제는 필자의 CSV 파일에서 필터링되고 출력 된 데이터 행을 계산하는 방법을 모르는 것입니다.PHP를 사용하여 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 문에 의해 필터링 된되는 데이터로한다.

지금까지 관리가 무엇
name,author,isbn,price 
name,author,isbn,price 
name,author,isbn,price 
name,author,isbn,price 

은 다음과 같다 :

CSV 파일과 같은 값을 포함

<?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에서 최고가 아니므로 도움을 주시면 대단히 감사하겠습니다.

답변

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>'; 
} 
} 
+0

매번 다시 선언하지 않으면 항상 1이되지는 않습니다. – Pitchinnate

+0

아아, 나는 항상 실수를 가장 쉽게한다. 빠른 답장을 보내 주셔서 감사합니다! – Deen

0

다음 줄을 이동해보십시오. while 루프

+0

당신은 또한 $ number = count ($ booklist); 루프 후 – splash21

0

$number

$booklist = array(); 

항상 1이 될 것 (또는 정의가 하나도 없다있다). 배열을 계산하는 대신 루프 앞에 $number=0;을 설정하고 사용하십시오. $number++;