php:将数组与mysql结果合并,并按数组键对它们进行排序

时间:2011-06-24 00:30:10

标签: php mysql arrays sorting merge

基本上我正在为我的网站构建一个serch引擎,但我的sql数据库基本上包含两组表(一组用于站点上的页面,另一组用于文件(.doc等))

我有popluate工作,我得到它返回页面的结果,现在我想搜索两个页面和文件,我想出了运行2个查询(因为2个表集)然后合并这些2将结果数组合成一个,然后按'出现'对它们进行排序,由查询添加。但输出与输入数组不匹配。无论如何一些代码给你一些工作

// Search the DB for pages
$page_result = mysql_query("SELECT p.page_url AS url, COUNT(*) AS occurrences FROM page p, word w, occurrence o WHERE p.page_id = o.page_id AND w.page_word_id = o.page_word_id AND w.word_word LIKE '' '" . $stemmed_string . "' '%' GROUP BY p.page_id ORDER BY occurrences DESC") // LIMIT " . $results . "")
or die("Invalid query: " . mysql_error());

// Search the DB for files
$file_result = mysql_query("SELECT f.file_url AS url, COUNT(*) AS occurrences FROM files f, filenames fn, fileoccurrence fo WHERE f.file_id = fo.file_id AND fn.file_word_id = fo.file_word_id AND fn.file_word LIKE '' '" . $stemmed_string . "' '%' GROUP BY f.file_id ORDER BY occurrences DESC")
or die ("Invalid query: " . mysql_error());

$page_array = mysql_fetch_array($page_result);
$file_array = mysql_fetch_array($file_result);


$results = array_merge((array)$page_array, (array)$file_array);

带有var转储的搜索项(a)的输出如下所示

  

array(4){[0] => string(33)“/ index.php?page = footy_tipping.htm”[“url”] => string(33)“/ index.php?page = footy_tipping.htm”[1] => string(4)“1272”[“occurrence”] => string(4)“1272”}

     

array(4){[0] => string(43)“/ files /forms / misc /Adjustment%20TEMPLATE.xls”[“url”] => string(43)“/ files /forms / misc /Adjustment%20TEMPLATE.xls”[1] => string(1)“2”[“occurrence”] => string(1)“2”}

     

array(6){[0] => string(33)“/ index.php?page = footy_tipping.htm”[“url”] => string(43)“/ files /forms / misc /Adjustment%20TEMPLATE.xls”[1] => string(4)“1272”[“occurrence”] => string(1)“2”[2] => string(43)“/ files /forms / misc /Adjustment%20TEMPLATE.xls”[3] => string(1)“2”}

它们的排序方式与上面的变量相同

在手册中查看了一下,并没有真正有用的知识如何通过key =>对数组进行排序值(例如sort($ results ['occurrence'],DESC))

任何帮助都会得到帮助,谢谢你们:)

2 个答案:

答案 0 :(得分:1)

如何在sql中作为联盟?

SELECT * FROM (    
    SELECT p.page_url AS url,
        COUNT(*) AS occurrences
    FROM page p, word w, occurrence o
    WHERE p.page_id = o.page_id
        AND w.page_word_id = o.page_word_id
        AND w.word_word LIKE '' '" . $stemmed_string . "' '%'
    GROUP BY p.page_id
    UNION
    SELECT f.file_url AS url,
        COUNT(*) AS occurrences
    FROM files f, filenames fn, fileoccurrence fo
    WHERE f.file_id = fo.file_id
        AND fn.file_word_id = fo.file_word_id
        AND fn.file_word LIKE '' '" . $stemmed_string . "' '%'
    GROUP BY f.file_id
) t
ORDER BY occurrences DESC

答案 1 :(得分:0)

你看看array_multisort吗?你必须做这样的事情:

<?php
// Obtain a list of columns
foreach ($results as $key => $row) {
    $occurrences[$key]  = $row['occurrences'];
}

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($occurrences, SORT_DESC, $results);
?>