Sort on date inside foreach loop with php


March 2019


20 time


I am trying to build a function that displays the reviews from an external json feed in a loop with php. Everything works fine, except the sorting.

I would like to sort the items based on date. This is the actual code which i created:

$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	

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>
<?php $count++; } ?>

1 answers


Может быть, что-то вроде этого:

$dates = [];
foreach ($reviews->beoordelingen as $i => $review)
    $dates[$i] = $review->date_created;
asort($dates); // this will sort array by values but keep keys attached to values
foreach (array_keys($dates) as $i)
    $review = $reviews->beoordelingen[$i];
    // rest of your code

Редактирование: на самом деле есть лучший способ сделать это с usort()

function date_compare($a,$b)
    return strcmp($a->date_created,$b->date_created);
usort($reviews->beoordelingen, 'date_compare');
foreach ($reviews->beoordelingen as $review)
    // rest of your code