phparrayssortingmultidimensional-arrayarray-multisort

Sort an associative array of related rows by a row of dates formatted as m/d/Y


My array has an array for each field (i.e date, name, etc.). How do I sort the array by date? Should I create another array? Can I use sort or unsort here. If yes, how? Here is my array:

Array
(
    [date] => Array
        (
            [0] => 03/11/2019
            [1] => 03/19/2019
            [2] => 03/15/2019
            [3] => 12/15/2018
        )

    [name] => Array
        (
            [0] => Lowa
            [1] => Stephanie
            [2] => Allan
            [3] => Joffer
        )

    [number] => Array
        (
            [0] => 178989898
            [1] => 111111111
            [2] => 222222222
            [3] => 333333333
        )

    [unit] => Array
        (
            [0] => HR
            [1] => VPP
            [2] => 
            [3] => OAT
        )

    [department] => Array
        (
            [0] => Chemistry
            [1] => IT
            [2] => Lab
            [3] => Contractor
        )

) 

At the end, my first element will be: 03/19/2019 Stephanie 111111111 VPP IT


Solution

  • I think your data can be better organized:

    $newArr = Array
    (
        [0] => Array
            (
                [date] => 03/11/2019
                [name] => Lowa
                [number] => 178989898
                [unit] => HR
                [department] => Chemistry
            )
    
        [1] => Array
            (
                [date] => 03/19/2019
                [name] => Stephanie
                [number] => 111111111
                [unit] => VPP
                [department] => IT
            )
    
        [2] => Array
            (
                [date] => 03/15/2019
                [name] => Allan
                [number] => 222222222
                [unit] =>
                [department] => Lab
            )
    
        [3] => Array
            (
                [date] => 12/15/2018
                [name] => Joffer
                [number] => 333333333
                [unit] => OAT
                [department] => Contractor
            )
    );
    

    Then, you can simply sort it by:

    function cmp($a, $b) {
      if ($a["date"] == $b["date"]) return 0;
      return ($a["date"] < $b["date"]) ? -1 : 1;
    }
    
    usort($newArr, "cmp");
    

    Please be warned that dates in the format "Month/Day/Year" ar not alphabetically sortable.
    You definitively should use a Year/Month/Day format for your dates, or write a more specific cmp() function...

    UPDATE: To answer OP's question in comment: just reverse $row and 'field' order:

    for ($row = 0; $row < count($date); $row++) {
      $newArr[$row]['date'] = $date[$row];
      $newArr[$row]['name'] = $name[$row];
      ...
    }