phparrayssortingdatearray-multisort

PHP using array_multisort to sort multiple arrays by date


I have around five arrays, where one of them is containing dates. I would like to sort these after the array containing dates. I know how to sort the date array using "usort". I also know how to sort multiple arrays using "array_multisort", but do not know how to combine these. Is there a way doing this? I hope you can help, and tell me if you need more information to solve my problem :)

Edit:

Here are my arrays:

$fid=array(1, 2, 3, 4, 5, 6, 7, 8);
$ftitle=array("Title1", "Title2", "Title3", "Title4", "Title1", "Title2", "Title3", "Title4");
$fbeskrivelse=array("Beskrivelse1", "Beskrivelse2", "Beskrivelse3", "Beskrivelse4", "Beskrivelse1", "Beskrivelse2", "Beskrivelse3", "Beskrivelse4");
$fstøtter=array(2, 15, 7, 10, 3, 4, 5, 6);
$fstartdato=array('11-01-2012', '01-01-2014', '01-01-2015', '09-02-2013', '01-01-2013', '11-01-2017', '01-01-2018', '01-01-2019');

So this is the kind of result I want (after the sorting):

$fid=array(1, 3, 4, 2, 5, 6, 7, 8);
$ftitle=array("Title1", "Title3", "Title4", "Title2", "Title1", "Title2", "Title3", "Title4");
$fbeskrivelse=array("Beskrivelse1", "Beskrivelse3", "Beskrivelse4", "Beskrivelse2", "Beskrivelse1", "Beskrivelse2", "Beskrivelse3", "Beskrivelse4");
$fstøtter=array(2, 7, 10, 15, 3, 4, 5, 6);
$fstartdato=array('11-01-2012', '01-01-2013', '09-02-2013', '01-01-2014', '01-01-2015', '11-01-2017', '01-01-2018', '01-01-2019');

Solution

  • If I'm understanding correctly, you have (lets say 3) arrays that you want to sort, one of which contains dates, and you want to sort by the dates, and since multisort does not support a callback or sort on dates, you aren't sure what to do?

    e.g.

    $arr1 = array('2019-05-15', '2019-05-17', '2019-05-13')
    $arr2 = array('Wed','Fri','Mon');
    $arr3 = array('Pork','Steak','Chicken');
    

    If it were me, I'd probably just parse the dates into unix_time in a new array and use that new array as my sorting "key" to sort the rest, since multisort can do numbers.

    (Not tested, just my theory)

    $key = array_map('strtotime', $arr1);
    array_multisort($key, SORT_ASC, SORT_NUMERIC, $arr1, $arr2, $arr3);