0

Is there a way to use array_multisort with a custom order by? I need the results to display in date order with the first date being the date closest to today's, as you can see from the code below the matchDate field comes through as a string which I later convert to a date value.

 foreach($matchLists as $matchList)
 {

   $fixtures[] = $matchList['matchDate'];

 }

array_multisort($fixtures, SORT_DESC, $matchLists);


$newlist = array();

  foreach($matchLists as $key => $matchitem)

{
   if(array_key_exists('matchDate', $matchitem))
  {   

      $newlist[$matchitem['matchDate']][$key] = ($matchitem);

   }


 }
   foreach($newlist as $key => $value)
     {
      $fixtureDate = date('D j M Y ga', strtotime($key));
      }
rmsGreig
  • 37
  • 1
  • 9

1 Answers1

0

Yes, take a look at one of my previous answer on SO:

<?php    
$events = array(
    'event1' => array(
        'event_name' => 'Title for Event 1',
        'event_date' => '2017-11-1'
    ),
    'event3' => array(
        'event_name' => 'Title for Event 1',
        'event_date' => '2017-10-13'
    ),
    'event4' => array(
        'event_name' => 'Title for Event 1',
        'event_date' => '2017-11-10'
    ),
    'event2' => array(
        'event_name' => 'Title for Event 1',
        'event_date' => '2017-10-22'
    ),
);

function date_compare($a, $b)
{ 
    // note that the variables are calling for the date part of the array
    // if you are using assoc array from mysql just change the value
    // to your row name
    $t1 = strtotime($a['event_date']);
    $t2 = strtotime($b['event_date']);
    return $t1 - $t2;
}    
usort($events, 'date_compare');
print_r($events);

Here you have an array with the date, you create the date_compare function and then usort to sort the array based on the date.

Hope this helps

Sam
  • 2,856
  • 3
  • 18
  • 29
  • thanks, this has it now showing at least in the correct date order although earliest date first, much tidier though – rmsGreig Nov 12 '17 at 20:14
  • You can modify the function to also select the closest date to today, and even maybe remove the past dates – Sam Nov 12 '17 at 20:15