Search code examples
phpsortingmultidimensional-arraycmp

PHP sorting a multidimensional Array by 3 values


I want to sort a mulitdimensional array by the values position (can only be 1 or 0), the date and the time. The arrays with position = 1 should be first, and they should be sorted by date and time. The array with position = 0 should come after the ones with position = 1 and should also be sorted by date and time

Array
(
[001] => Array
    (
        [position] => 1
        [Date] => 28.04.2013
        [Time] => 00:21:38
    )

[002] => Array
    (
        [position] => 1
        [Date] => 28.04.2013
        [Time] => 00:27:07
    )

[003] => Array
    (
        [position] => 0
        [Date] => 28.04.2013
        [Time] => 00:15:06
    )

[004] => Array
    (
        [position] => 0
        [Date] => 28.04.2013
        [Time] => 00:26:09
    )

)

Thats how I want the array to be after sorting:

Array
(
[002] => Array
    (
        [position] => 1
        [Date] => 28.04.2013
        [Time] => 00:27:07
    )

[001] => Array
    (
        [position] => 1
        [Date] => 28.04.2013
        [Time] => 00:21:38
    )

[004] => Array
    (
        [position] => 0
        [Date] => 28.04.2013
        [Time] => 00:26:09
    )

[003] => Array
    (
        [position] => 0
        [Date] => 28.04.2013
        [Time] => 00:15:06
    )

)

I've tried a few functions but none of the worked right. Either the arrays with position = 1 are the last ones or all arrays just sort by date and time. I can`t figure it out by myself. Thanks in advance and sorry if my English is bad.


Solution

  • Where the original dataset is in an array named $array...

    $positions = $datetimes = array();
    
    foreach($array as $k => $v) {
    
       $positions[$k] = $v['position'];
       $datetimes[$k] = strtotime($v['Date']. ' ' .$v['Time']);
    
    }
    
    array_multisort($positions, SORT_DESC, $datetimes, SORT_DESC, $array);
    

    Based on comparing your data, it appears you want to sort by position DESC first, then Time (and assuming date too) DESC, so that's what this does.

    Working example: http://codepad.org/exc5Dhq8