2013-01-11 188 views
1

我有一個查詢,它在我的貸款表中查找前10個最借貸的書籍,但是我想將這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>"; 

} 
+2

'$ titles [] = $ row ['title'];' –

+0

問題在哪裏? – ficuscr

+0

@RocketHazmat謝謝! – user1930227

回答

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>"; 
+0

謝謝!非常感謝 – user1930227

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); 
+0

哦,好的,謝謝! – user1930227

0

應填寫您的數組中循環,而不是在單獨的循環中:

$count = 0; 
while($row = mysql_fetch_array($result)) 
{ 
    echo $row['title']; 
    echo "<br>"; 
    if ($count < 10) 
    { 
    array_push($titles, $row); 
    } 
    $count++; 
} 
+0

啊,謝謝Jeroen! – user1930227

+0

@ user1930227請注意,您需要推送'$ row',我之前複製了您的代碼(錯誤地...)。 – jeroen

+0

很好,謝謝! – user1930227