我有一个查询,它在我的贷款表中找到了十大最借出的书籍,但我想将这十个值存储到一个数组中,以便我可以再次使用该数组。这是我到目前为止的代码...感谢您提前提供任何帮助!
//select a database to work with
$selected = mysql_select_db("ds2",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT book.title, book.book_id, count(book.book_id) AS count_book_id, loan.book_id FROM book
INNER JOIN loan ON book.book_id = loan.book_id
GROUP BY book.book_id ASC
ORDER BY count(book.book_id) DESC");
$titles = array();
while($row = mysql_fetch_array($result))
{
echo $row['title'];
echo "<br>";
}
echo "<br><br>";
for($index = 1; $index <= 10; $index++)
{
array_push($titles,$result[$row]);
print_r($titles);
echo "<br>";
}
答案 0 :(得分:2)
而不是echo $row['title']
您可以使用下面的代码将它们存储到数组中
$titles[] = $row['title'];
使用数组概念稍后访问它们。
$titles[0]; // 1st item
$titles[1]; //2nd item
您甚至可以使用foreach循环遍历所有项目。
foreach($titles[] as $title)
echo $title;
下面将允许您获取逗号分隔的字符串(仅在您需要时提供信息)
$comma_separated_titles = implode(",", $titles);
答案 1 :(得分:0)
尝试,
while($row = mysql_fetch_array($result))
{
echo $row['title'];
$arr[] = $row['title']; //Store in an array
echo "<br>";
}
echo "<br><br>";
//Since you need only 10 values, else this for loop is not required.
for($index = 1; $index <= 10; $index++)
$titles[] = $arr[$index]['title'];
unset($arr); //unset the original array if you don't need it anymore.
print_r($titles); //Print top 10 values
echo "<br>";
答案 2 :(得分:0)
你应该在循环中填充数组,而不是在单独的循环中填充:
$count = 0;
while($row = mysql_fetch_array($result))
{
echo $row['title'];
echo "<br>";
if ($count < 10)
{
array_push($titles, $row);
}
$count++;
}