Question

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.

Was it helpful?

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

OTHER TIPS

Take a look at the function usort(), which takes an array and a comparison function as parameters.

Write a comparaison function that can compare two of your array elements:

  • compare position

  • if positions are equal, then compare date

  • if dates are equal, then compare time

use usort() - "Sort an array by values using a user-defined comparison function"

function your_func($a, $b) {
    $pos = $b["position"] - $a["position"];
    if($pos) return $pos;

    $date = strtotime($b["Date"]) - strtotime($a["Date"]);
    if($date) return $date;

    $time = strtotime($b["Time"]) - strtotime($a["Time"]);
    return $time;
}
usort($arr, "your_func");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top