我正在寻找一种将 MySQL 和 XML 数据合并在一起的方法,因此我可以按时间戳对它们进行排序。理想的情况是这样的:
SELECT timestamp, title
FROM news
UNION ALL
SELECT timestamp, title
FROM xmlsource('local.xml')
ORDER BY timestamp DESC
这样的事情可能吗?或者他们是否有任何其他方式来合并数据源并对它们进行排序?感谢您提供正确方向的任何指示。
我不知道这会有多有效,但你可以自己测试一下。这里是:
<?php
$sql = 'SELECT timestamp, title FROM news ORDER BY timestamp DESC';
$run = mysql_query( $sql, $link );
$result = array();
if( $run && mysql_num_rows( $run ) ) {
while( ( $fetch = mysql_fetch_assoc( $run ) ) !== false ) {
$time = $fetch[ 'timestamp' ];
$title = htmlspecialchars( $fetch[ 'title' ], ENT_COMPAT, 'UTF-8' );
$result[ $time ][] = $title;
// this is an array, in case multiple title have same timestamp.
}
}
$xml = simplexml_load_file( 'local.xml' );
$xpath = $xml->xpath( '//story' );
foreach( $xpath as $story ) {
$time = $story->time;
$title = (string) $story->headline;
$result[ $time ][] = $title; // append this to the results array.
}
// sort by timestamp ascending
arsort( $result );
?>
希望能帮助到你。