-3

Hi I have a list of arrays which im getting using a foreach loop that each contain a date.

I want to do another foreach loop to output each array but order them based on the date.

It is currently outputting:

Array
(
    [0] => 31.08.2016
    [1] => prize10
)
Array
(
    [0] => 31.07.2017
    [1] => prize10
)
Array
(
    [0] => 31.08.2017
    [1] => prize6
)
Array
(
    [0] => 21.08.2017
    [1] => prize6
)

and the code i have is :

foreach ( $unclaimed_users  as $unclaimed_user ) {
   $a = get_user_meta($unclaimed_user->ID , "unclaimed");
   $unserialized = unserialize($a[0]);
  //echo $unserialized[0]; //Date
  //echo $unserialized[1]; //Prize

    print_r($unserialized);
}

But these are in no specific order, how can I make them output based on the most recent date

Dgeorgex000000
  • 93
  • 1
  • 2
  • 8

2 Answers2

3

You can make use of usort:

function sort_date($a, $b)
{
    $d1 = strtotime($a[0]);
    $d2 = strtotime($b[0]);
    return $d2 - $d1;
}

$array = [['31.08.2016', 'prize10'], ['31.07.2017', 'prize10'], ['31.08.2017', 'prize6'], ['21.08.2017', 'prize6']];

usort($array, 'sort_date');

print_r($array);

Gives:

Array
(
    [0] => Array
        (
            [0] => 31.08.2017
            [1] => prize6
        )

    [1] => Array
        (
            [0] => 21.08.2017
            [1] => prize6
        )

    [2] => Array
        (
            [0] => 31.07.2017
            [1] => prize10
        )

    [3] => Array
        (
            [0] => 31.08.2016
            [1] => prize10
        )

)
Thamilhan
  • 13,040
  • 5
  • 37
  • 59
  • So how would i get them values into a variable as you said: $array = [['31.08.2016', 'prize10'], ['31.07.2017', 'prize10'], ['31.08.2017', 'prize6'], ['21.08.2017', 'prize6']]; – Dgeorgex000000 Aug 31 '17 at 13:30
  • `$unserialized[] = unserialize($a[0])`. I thought you got these and I directly went for sorting – Thamilhan Aug 31 '17 at 13:37
  • Sorr yim struggling to make this work could you incorporate it into my code above please – Dgeorgex000000 Aug 31 '17 at 14:02
0

First of all, I think you need to merge your arrays like this :

foreach $arrays as $array) {
    $merged[] = array(date('Y-m-d', strtotime($array[0])) => $array[1];
}

and here you will obtain this :

Array (
    [2016-08-31] => prize10
    [2017-31-07] => prize10
    [2017-31-08] => prize6
    [2017-21-08] => prize6
)

After that, you can sort it and use it easily !

For example to get date and value, use this :

foreach($merged as $date => $prize) {
    echo $date . ':' . $prize;
}

To sort the array use ksort($merged); Mor info here : http://php.net/ksort

Meloman
  • 3,558
  • 3
  • 41
  • 51