phparrayssortingmultidimensional-array

Sort a 2d array by one column then another column


I have the following array that I'm trying to sort:

[0]=>Array
 {
   [date_test] => 2016-01-01
   [last_name] => Smith
 }
[1]=>Array
{
   [date_test] => 2015-01-01
   [last_name] => Davis
 }
[2]=>Array
{
   [date_test] => 2015-01-01
   [last_name] => Smith
}

I'm trying to get the desired output:

Davis 2015-01-01
Smith 2015-01-01
Smith 2016-01-01

Here is what I'm using as code:

foreach ($total_records as &$test) {
  $test[] = $this->sortArray($test,array('patient_last_name','issued_at'));
}

sortArray( $data, $field )
{
   $field = (array) $field;
    uasort( $data, function($a, $b) use($field) {
    $retval = 0;
    foreach( $field as $fieldname )
    {
        if( $retval == 0 ) $retval = strnatcmp( $a[$fieldname],  $b[$fieldname] );
    }
    return $retval;
} );
return $data;
}

Any idea on how to to get the desired output?


Solution

  • assign your array of arrays to $mylist

    Get a list of sort columns and their data to pass to array_multisort

    $sort_vals = array();
    foreach($mylist as $k=>$v) {
        $sort_vals['date_test'][$k] = $v['date_test'];
        $sort_vals['last_name'][$k] = $v['last_name'];
    }
    

    sort by event_type desc and then title asc

    array_multisort($sort_vals['last_name'], SORT_DESC, $sort_vals['date_test'], SORT_ASC,$mylist);