使用while循环获取JSON返回列表Book

时间:2014-04-10 19:54:41

标签: php json while-loop

我想创建一个可以作为有效JSON输出返回的书籍列表。应该只有一个JSON输出输出书籍列表。我现在有这个问题但是问题只是将while循环的最后一本书添加到列表Book中,这就是我想要返回的内容。

//Return each book found given search.  
while(list($book_id, $title, $authors, $description, $price) = mysqli_fetch_row($search)){  

$thisBook = array("book_id"=>$book_id,"title"=>$title,"authors"=>$authors,"description"=>$description,"price"=>$price);

$Book = array();
$Book[] = $thisBook;

}


//JSON Return
$success = TRUE;
$message = "Success";
$output = $Book;
echo json_encode($output);

我怎么能这样做?感谢

1 个答案:

答案 0 :(得分:0)

$Book = array();

while(list($book_id, $title, $authors, $description, $price) = mysqli_fetch_row($search)){  

$thisBook = array("book_id"=>$book_id,"title"=>$title,"authors"=>$authors,"description"=>$description,"price"=>$price);


$Book[] = $thisBook;

}

你在循环中覆盖了数组,所以得到了最后的数据。 因此,在循环之外声明$Book = array();