1

我有一个查询,可以在我的外借表中找到前 10 本书,但是我想将这十个值存储到一个数组中,以便我可以再次使用该数组。这是我到目前为止的代码......提前感谢您的帮助!

//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>";

}
4

3 回答 3

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);
于 2013-01-11T17:21:51.430 回答
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>";
于 2013-01-11T17:21:57.480 回答
0

您应该在循环中填充数组,而不是在单独的循环中填充数组:

$count = 0;
while($row = mysql_fetch_array($result))
{
  echo $row['title'];
  echo "<br>";
  if ($count < 10)
  {
    array_push($titles, $row);
  }
  $count++;
}
于 2013-01-11T17:22:48.940 回答