0

So im getting very confused about the sorting functions in php, and wondered if someone could point me in the right direction.

The following is a multidimensional array, that i wish to sort first my date, and then by time. Such that if 2 dates are the same, the earlier time will show first.

can this be done and how?

the top array is called $events

Thank you!

array(4) {
  [0]=>
  array(3) {
    ["name"]=>
    string(4) "Jack"
    ["date"]=>
    string(8) "21.11.13"
    ["time"]=>
    string(5) "17:36"
  }
  [1]=>
  array(3) {
    ["name"]=>
    string(4) "Mike"
    ["date"]=>
    string(8) "21.11.13"
    ["time"]=>
    string(5) "07:30"
  }
  [2]=>
  array(3) {
    ["name"]=>
    string(6) "Thomas"
    ["date"]=>
    string(8) "10.11.12"
    ["time"]=>
    string(5) "18:21"
  }
}
Malibur
  • 1,695
  • 5
  • 22
  • 31

1 Answers1

0

You need array_multisort() for this. In your case, you need to extract the columns you want to sort by from your multidimensional array and pass them as params to array_multisort. Here's the solution to your problem:)

/*walk the array and extract the columns needed for sorting*/
foreach($yourarray as $key=>$row){   
  $date[$key] = $row['date'];  
  $time[$key] = $row['time']; 
} 
/*sort the array */
array_multisort($date, SORT_ASC, $time, SORT_ASC, $yourarray);
  • For some reason that didn't work, but this from the other post did: `# get a list of sort columns and their data to pass to array_multisort $sort = array(); foreach($event_array as $k=>$v) { $sort['date'][$k] = $v['date']; $sort['time'][$k] = $v['time']; } # sort by event_type desc and then title asc array_multisort($sort['date'], SORT_ASC, $sort['time'], SORT_ASC,$event_array); ?>` – Malibur Nov 12 '13 at 20:12
  • Okay i realise that it is horrible to read- dont know how to format comments properly. I got it working by following the link that alexander Kuzmin gave me, and its a little bit different from yours. I dont really understand whats going on, so i dont know why. Looks like he extract into a new array that he call sort, and use that to sort the initial array up against? – Malibur Nov 12 '13 at 20:16