我正在尝试构建一个函数,用 php 循环显示来自外部 json feed 的评论。除了排序之外,一切正常。
我想根据日期对项目进行排序。
<?php
$json_url = get_field('review_json_url', 'option'); // path to your JSON file
$data = file_get_contents($json_url); // put the contents of the file into a variable
$reviews = json_decode($data); // decode the JSON feed
?>
<?php
$count=0;
foreach ($reviews->beoordelingen as $review) if ($count < 10) {
// vars
$publish_date = $review->date_created;
$name = $review->klant_naam;
$title = $review->title;
$content = $review->tekst;
$date = new DateTime($publish_date);
?>
<div class="review">
<h3 class="name"><?php echo $name; ?></h3>
<h5 class="location"><?php echo $date->format('d-m-Y'); ?></h5>
<h4 class="subtitle">"<?php echo $title; ?>"</h4>
<div class="content">
<p><?php echo $content; ?></p>
</div>
</div>
<?php $count++; } ?>
最佳答案
通常在这些情况下,我发现最好在显示之前组织数据。下面我通过设置 1 个 foreach
来处理“逻辑”和 1 个 foreach
来处理实际显示数据来完成此操作。
从这里开始,就像添加自定义排序算法一样简单。 (有关更深入的示例,请参阅 PHP Sort Array By SubArray Value)
<?php
$sorted_reviews = array();
foreach ($reviews->beoordelingen as $review) {
$date = new DateTime($publish_date);
$sorted_reviews[] = array(
'publish_date' => $review->date_created,
'name' => $review->klant_naam,
'title' => $review->title,
'content' => $review->tekst,
'date' => $date,
'sortable' => $date->getTimestamp(),
);
}
usort($sorted_reviews, 'sortByOption');
function sortByOption($a, $b) {
return strcmp($a['sortable'], $b['sortable']);
}
$count=0;
foreach ($sorted_reviews as $review) if ($count < 10) {
?>
<div class="review">
<h3 class="name"><?php echo $review['name']; ?></h3>
<h5 class="location"><?php echo $review['date']->format('d-m-Y'); ?></h5>
<h4 class="subtitle">"<?php echo $review['title']; ?>"</h4>
<div class="content">
<p><?php echo $review['content']; ?></p>
</div>
</div>
<?php $count++; } ?>
关于php - 使用 php 对 foreach 循环内的日期进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55169839/