2011-04-11 29 views
0

我有一個照片網站,我試圖對MySQL數據庫執行查詢。該查詢是針對稱爲「title_keyword」的「標題」和「關鍵字」的拼接字段。 我想獲取搜索結果,並通過一個名爲'sort_priority'的新形成的變量對它們進行排序,該變量正在檢查搜索詞是否位於'標題'字段中。如果它在'標題'字段中,那麼我想要分配1的值,如果不在標題字段中,則值爲2.結果數組將按'sort_priority'進行排序並輸出到屏幕。如何從MySQL結果創建php數組,執行計算,度假村數組,目前的結果

這裏是我用PHP和MySQL使用的邏輯:

1)查詢MySQL數據庫並分配變量。 (這只是正常)

2)取結果,每個字段賦值給一個變量,創建執行上的一個變量計算一個新的變量返回

$data_array=array(); 
// get each row 
while($row = mysql_fetch_array($result)) 
{ 
//get data 
$image_id = "{$row['image_id']}"; 
$title = "{$row['title']}"; 
$imageurl = "{$row['imageurl']}"; 


// Create sort_priority to identify if search word is in title field. 
//If it is then set to 1 to force this higher in the result list after sorting 

$sort_priority = 2; 
if(stristr($title,$search)) 
{ $sort_priority = 1;} 

一切上面這點作品。現在對於我所陷入的部分而言。如何創建數據並將其添加到數組,然後對我的新$ sort_priority變量進行排序。

這裏是我寫什麼,但它只是不工作**

// Create array and sort by title then keyword (tk_sort) 
$data_array = array(
'image_id' => $image_id, 
'title' => $title, 
'imageurl' => $imageurl, 
'sort_priority' => $sort_priority); 

// Obtain a list of columns 
foreach ($data_array as $key => $row) { 
    $image_id[$key] = $row['image_id']; 
    $title[$key] = $row['atitle']; 
    $imageurl[$key] = $row['imageurl']; 
    $sort_priority[$key] = $row['sort_priority']; 
} 

// Sort the data with volume descending, edition ascending 
// Add $data as the last parameter, to sort by the common key 

array_multisort($sort_priority, SORT_ASC); 

// end of array creation and sort 

3)輸出新排序的數組表

不確定如何從中獲取數據。我必須使用循環或什麼?

回答

0

你可以讓MySQL完成大部分工作。這應該工作(自己沒有嘗試過):

SELECT CONCAT_WS('-', `title`, `keyword`) AS search_term, 
IF(INSTR(`search_term`, 'your_search_value_here') > 0, 1, 2) AS priority_key, 
`image_id`, `imageurl` 
FROM table_name_here 
ORDER BY `priority_key`; 

HTH。

+0

謝謝!我用這個,並不得不修改它的一些工作。另外,該語句不適用於IF語句中創建的search_term字段。現在我想看到的是,如果有一種方法可以在search_term中找到搜索值'your_search_value_here',那麼只有它是一個完整的單詞而不僅僅是一個字符串。有任何想法嗎? – 2011-04-12 04:56:14