2013-07-08 89 views
-1

我2個組合查詢:$stmt1$stmt2到第三陣列($results)合併所有結果,並利用它們來輸出1 RSS提要...飼料的作品,但它是從上市的所有$stmt1由結果第一event_start和然後,從$stmt2通過event_start結果...我想既有 '組合拳' 的結果event_start數組排序問題

<? 
header("Content-Type: application/rss+xml; charset=ISO-8859-1"); 

$rssfeed = "<?xml version='1.0' encoding='ISO-8859-1'?>"; 
$rssfeed .= "<rss version='2.0'>"; 
$rssfeed .= "<channel>"; 
$rssfeed .= "<title></title>"; 
$rssfeed .= "<link></link>"; 
$rssfeed .= "<description></description>"; 
$rssfeed .= "<language>en-us</language>"; 

$db1 = new PDO('mysql:host='.$db_host1.';dbname='.$db_name1,$db_username1,$db_pass1); 
$db2 = new PDO('mysql:host='.$db_host2.';dbname='.$db_name2,$db_username2,$db_pass2); 

$db1->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING); 
$db2->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING); 

$stmt1 = $db1->query("SELECT event_start, title, s_description FROM special_events WHERE event_start >= NOW() ORDER BY event_start ASC"); 
$stmt2 = $db2->query("SELECT event_start, title, s_description FROM special_events WHERE event_start >= NOW() ORDER BY event_start ASC"); 

$results = array_merge($stmt1->fetchAll(PDO::FETCH_ASSOC), $stmt2->fetchAll(PDO::FETCH_ASSOC)); 

$events = array(); 
foreach ($results as $key => $row) {  

$rssfeed .= "<item>"; 
$date[$key] = $row['event_start']; 
$rssfeed .= "<title>".htmlentities($row['title'])."</title>"; 
$rssfeed .= "<description>".htmlentities($row['s_description'])."</description>"; 
$rssfeed .= "<link>http://link.com</link>"; 
$rssfeed .= "<pubdate>".$row['event_start']."</pubdate>"; 
$rssfeed .= "</item>"; 
} 
$rssfeed .= '</channel>'; 
$rssfeed .= '</rss>'; 

array_multisort($date, SORT_ASC, $results); //not working 

echo ($rssfeed); 
?> 

回答

1

只需您$results陣列foreach調用之前進行排序:

usort($results, function($row_a, $row_b) { 
    if ($row_a['event_start'] > $row_b['event_start']) { 
     return 1; 
    } else if ($row_a['event_start'] < $row_b['event_start']) { 
     return -1; 
    } else { 
     return 0; 
    } 
}); 

請注意,此代碼進行了非常基本的比較,它只適用於字符串或數字。如果$row_a$row_b是日期字符串,則需要將它們轉換爲DateTime。我希望你明白這個主意。