【发布时间】:2018-03-16 06:11:45
【问题描述】:
我的目标不是将任何项目保存到数据库,而只是显示实时流。
我正在从赫芬顿邮报获取 RSS 提要
http://www.huffingtonpost.com/section/front-page/feed
我有一个包含 Huff 最近 50 篇文章的 WordPress 数组 (PHP)。
$rss = fetch_feed($feed_url);
我希望我的 RSS 提要每天仅显示 X 的唯一帖子总数。为了简单起见,我只是要显示最接近 24 / X 间隔的帖子。
为了演示,让我们使用 3。Feed 会吐出最接近 8 点、16 点(下午 2 点)和 24 点(午夜)或(0、8 和 16 点)发布的帖子。
在 PHP 中,如何通过发布的时间变量对对象数组进行排序,然后找到最接近该时间的帖子?现在我正在做一个非常迂回的方式,目前甚至无法正常工作。
这是我目前的逻辑:
if(function_exists('fetch_feed')) {
$rss = fetch_feed(get_field('feed_url'));
if(!is_wp_error($rss)) : // error check
$maxitems = $rss->get_item_quantity(50); // number of items at 50
$rss_items = $rss->get_items(0, $maxitems);
endif;
// display feed items ?>
<h1><?php echo $rss->get_title(); ?></h1>
<?php
$coutner = 0;
$daily_max = 3; //how many unique feeds to display per day
$display_interval = floor(24 / $daily_max); //simple way to make even intervals
$posting_time = array(); //to store the times to post
foreach(range(0, $daily_max-1) as $i) {
$posting_time[$i] = $display_interval * $i;
}
$post_interval = 0;
$date = new DateTime();
$today = date("G"); //getting the current day's hour
$time_adjust = $today / $display_interval;
//adjust the posting times order so that its circular
while($today > $posting_time[0]){
$hold = array_pop($posting_time);
echo '<p>hold: ' . $hold;
array_unshift($posting_time,$hold);
}
$accessing = array_pop($posting_time);
?>
<dl>
<?php if($maxitems == 0){ echo '<dt>Feed not available.</dt>';}
else{
foreach ($rss_items as $item) : ?>
<?php
//as soon as the first item is newer than post time, output it & count that time slot as being filled
$rss_item_hour = $item->get_date('G');
if($rss_item_hour > $accessing){ ?>
<dt>
<a href="<?php echo $item->get_permalink(); ?>"
title="<?php echo $item->get_date('j F Y @ G'); ?>">
<?php echo $item->get_title(); ?>
</a>
</dt>
<dd>
<?php echo $item->get_description(); ?>
</dd>
<p>
<?php echo $item->get_date('j F Y | G');
?>
</p>
<?php $coutner = $coutner + 1;
$accessing = array_pop($posting_time);
}
else{echo '<p>else';} ?>
<?php endforeach; ?>
</dl>
<?php }} ?>
目前的主要错误是,有时while($today > $posting_time[0]){ 的循环移动会无限进行。而且循环似乎永远不会按计划进行。
【问题讨论】:
-
您是正确的,while 循环是问题,因为您从未在循环内更新 $today。如果它是真的,它将永远是真的,因为它永远不会被设置为其他任何东西。这绝对看起来过于复杂。我会尝试制定解决方案。
-
您是否真正关心显示的帖子在一天中的间隔是否均匀,或者只是为了简化它(提示:不关心要简单得多) ?从提要开始,您每天需要 3 件物品,还是过去 24 小时内只需要 3 件?是否保证每天/过去 24 小时内始终至少有 3 件商品?
-
那么,如果提要在凌晨 1 点检索,应该显示什么?由于下一个“里程碑”是上午 8 点,这意味着“最近的 4 个帖子”直到上午 8 点?那么,随着时间的推移,显示的帖子正在发生变化,因为可能会有更新的帖子“更接近”某个里程碑?阅读此内容,然后重新考虑您的问题,我会说xyproblem.info
-
既然您想要每 8 小时时间间隔(或 6 小时等...)的提要,您现在不应该只获取最后 x 小时的提要吗?
标签: php arrays wordpress loops rss