Search code examples
phparraysarray-multisort

array_multisort order by value closest to todays date


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));
      }

Solution

  • 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