H. Ferrence
H. Ferrence

Reputation: 8106

How to sort Multi-Dimensional Arrays in PHP where Keys are actually Values

I have a multi-dimensional array shown below that I want to sort by the 1st level dimension and then the 2nd level dimension within the 1st level.

I want the dates to be in chronological order and then then times, within the dates, to be in clock sequence.

Array
(
    [2014-05-17] => Array
        (
            [0] => 17:30
            [1] => 11:30
            [2] => 13:30
            [3] => 12:30
            [4] => 12:30
        )

    [2014-06-21] => Array
        (
            [0] => 17:30
            [1] => 10:30
            [2] => 13:30
            [3] => 09:30
            [4] => 12:30
            [5] => 09:30
            [6] => 12:30
        )

    [2014-05-18] => Array
        (
            [0] => 17:30
            [1] => 11:30
            [2] => 13:30
            [3] => 12:30
            [4] => 12:30
        )
)

Also, after I sort the times, I want to remove duplicates -- in other words I simply want the unique times within each date to be in clock order.

Here is what I would like to produce:

[2014-05-17] => Array ( [0] => 11:30 [1] => 12:30 [2] => 13:30 [3] => 17:30 )

[2014-05-18] => Array ( [0] => 11:30 [1] => 12:30 [2] => 13:30 [3] => 17:30 )

[2014-06-21] => Array ( [0] => 09:30 [1] => 10:30 [2] => 12:30 [3] => 13:30 [4] => 17:30 )

Upvotes: 0

Views: 124

Answers (1)

Alberto Delgado Roda
Alberto Delgado Roda

Reputation: 471

If your variable array name is $arrayDate, execute this:

ksort($arrayDate);
foreach($arrayDate as &$key){
    $key = array_unique($key);
    sort($key);
}

Upvotes: 1

Related Questions