DMS-KH
DMS-KH

Reputation: 2797

How to sort from higher to smaller value in foreach by using PHP?

I've generate a range of date from last months by using Foreach in PHP it worked ask well But I want to sort it from highest value to smaller than.

<?php
$begin = new DateTime('2015-11-01');
$end = new DateTime(date("Y-m-d"));
$end = $end->modify('+1 day');

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval, $end);
$i = 1;
foreach ($daterange as $in => $val) {

      $tr = '<tr>' .
            '<td>' . $i++ . '</td>' .
            '<td>' . $val->format("Y-m-d") . ' 13:00' . '</td>' .
            '</tr>';
     echo $tr;
     $tr =  '<tr>' .
            '<td>' . $i++ . '</td>' .
            '<td>' . $val->format("Y-m-d") . ' 18:00' . '</td>' .
            '</tr>';
     echo $tr;
 }
?>

Below is my result

1   2015-11-01 13:00
2   2015-11-01 18:00
3   2015-11-02 13:00
4   2015-11-02 18:00
5   2015-11-03 13:00

But But I want like this

1   2015-11-03 13:00
2   2015-11-03 18:00
3   2015-11-02 13:00
4   2015-11-02 18:00
5   2015-11-01 13:00
6   2015-11-01 18:00

Thanks for your help

Upvotes: 0

Views: 155

Answers (3)

Terabyte
Terabyte

Reputation: 455

You can use what is known as bubble sort : have a look on the code below, it sorts from max to min

function bubble_sort($arr) {
    $size = count($arr);
    for ($i=0; $i<$size; $i++) {
        for ($j=0; $j<$size-1-$i; $j++) {
            if ($arr[$j+1] > $arr[$j]) {
                swap($arr, $j, $j+1);
            }
        }
    }
    return $arr;
}

function swap(&$arr, $a, $b) {
    $tmp = $arr[$a];
    $arr[$a] = $arr[$b];
    $arr[$b] = $tmp;
}

/* test bubble sort */

$arr = array(31,3,2,55,15,7,4,90);

print("Before sorting");
print_r($arr);

$arr = bubble_sort($arr);
echo "<br/>";
print("After sorting by using bubble sort");
echo "<br/>";
print_r($arr);

Upvotes: 1

Luca Rainone
Luca Rainone

Reputation: 16468

foreach is not the right tool in this case. You should use while and Date::sub(interval):

$i = 1;
echo "<table>";
$current = clone $end;
while( ($val = $current) >= $begin) {
    $tr = '<tr>' .
        '<td>' . $i++ . '</td>' .
        '<td>' . $val->format("Y-m-d") . ' 13:00' . '</td>' .
        '</tr>';
    echo $tr;
    $tr =  '<tr>' .
        '<td>' . $i++ . '</td>' .
        '<td>' . $val->format("Y-m-d") . ' 18:00' . '</td>' .
        '</tr>';
    echo $tr;
    $current->sub($interval);
}

Upvotes: 1

sfandler
sfandler

Reputation: 640

I guess that new DatePeriod() returns its result already sorted. Looks like you want it backwards, if I understood your question correctly. With PHP's array_reverse, you can reverse an array. Placing the following line in front of your foreach-loop should give you the result you want:

$daterange = array_reverse($daterange);

Upvotes: -1

Related Questions