-1

我合并了 2 个查询:$stmt1$stmt2合并到第三个数组 ( $results) 中以合并所有结果并使用它们输出 1 个 rss 提要...提要有效,但它首先列出所有结果,然后列出来自...的结果...$stmt1我想按两个“组合”结果排序event_start$stmt2event_startevent_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);
?>
4

1 回答 1

1

只需在调用之前对您的数组进行排序$resultsforeach

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_aand$row_b是日期字符串,则需要将它们转换为 DateTime。我希望你能明白。

于 2013-07-08T16:44:15.967 回答